1、文件路径path=r'C:\Users\Desktop\'
2、获取路径下的特定文件
for item in os.listdir(path):
if item == 'file_name':
item_path = os.path.join(path, item) #####获取文件名为file_name的文件路径
3、打开该文件,获取特定行内容
fn3 = open(str(item_path),encoding='gb18030', errors='ignore')###如果文件类型比较特殊,可以加上这两句encoding='gb18030', errors='ignore'
lines = fn3.readlines()
fn3.close
for ls in lines:######遍历文件中每一行
if 'total time' in ls:#####如果特定行包含total time
score = ls.split('=')[1].split()[0] ##
如果为fn3 = open(str(item_path))
运行后出现UnicodeDecodeError: 'gbk' codec can't decode byte 0x81 in position 7234: illegal multibyte sequence
建议改为
fn3 = open(str(item_path),encoding='gb18030', errors='ignore')
4、全部代码为
path=r'C:\Users\Desktop\'
for item in os.listdir(path):
if item == 'file_name':
item_path = os.path.join(path, item) #####获取文件名为file_name的文件路径
fn3 = open(str(item_path),encoding='gb18030', errors='ignore')###如果文件类型比较特殊,可以加上这两句encoding='gb18030', errors='ignore'
lines = fn3.readlines()
fn3.close
for ls in lines:######遍历文件中每一行
if 'total time' in ls:#####如果特定行包含total time
score = ls.split('=')[1].split()[0] #####获取特定行中想要保存的数据