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

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]   #####获取特定行中想要保存的数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NDLilaco

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值