0
点赞
收藏
分享

微信扫一扫

打开路径下的文件,获取文件内特定行的内容

码农K 2022-04-05 阅读 56
python

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')
举报

相关推荐

0 条评论