Python 读写TXT 使用正表达式 读取部分文字
在很多python 中需要去读取TXT来实现应用的设置,这里提供一个方法,
读取TXT文件
try:
with open(file_name, "r") as f: # 打开文件
self.data = f.read() # 读取文件
# print(self.data)
f.close()
except BaseException:
print "索引不到文件"
with open(file_name, "w+") as f: # 打开文件 如果没有就创建
f.write(self.default_allocation)
self.data = self.default_allocation
# print(self.data)
f.close()
从读取的数据中正表达式分解
def Find_parameters(self,Find_data):
Find_data = r'\w*' + str(Find_data) + '[\s\S]*?;'
data_t = ''.join(re.findall(Find_data, self.data, flags=0))
data_t = ''.join(re.findall( r'\w*=[\s\S]*?;', data_t))
data_t = re.sub(str(Find_data), '', data_t) #删除 对应关键字
data_t = re.sub('[ =;]', '', data_t) #删除 多余的其他符合 保留字符和数字
print data_t
return data_t
def Find_parameters_Suffix(self,Find_data):
Find_data = r'\w*' + str(Find_data) + '[\s\S]*?;'
data_t = ''.join(re.findall(Find_data, self.data, flags=0))
data_t = ''.join(re.findall( r'\w*=[\s\S]*?;', data_t))
data_t = ''.join(re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', data_t)) #保留 后缀名
data_t = re.sub(str(Find_data), '', data_t) #删除 对应关键字
data_t = re.sub('[^A-Za-z0-9.]', '', data_t) #删除 多余的其他符合 保留字符和数字
# print data_t
return data_t
Find_parameters 返回的字符
Find_parameters_Suffix 返回的是后缀名
例如 我TXT文件中是
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxx
Set_Low_Shutdown_countdown = dc1.gif;#Only supports gif format
xxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxx
self.Find_parameters_Suffix('Set_Low_Shutdown_countdown') #获取的是‘.gif’
self.Find_parameters('Set_Low_Shutdown_countdown') #获取的是'dc1.gif';