欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python按行读取文件并找出其中指定字符串

时间:2021-02-27 14:31:16|栏目:Python代码|点击:

python按行读取文件并找出其中指定字符串

#coding=utf-8
import os, time, sys, re
 #reload(sys)
 #sys.setdefaultencoding("utf8")  # 不设置,否则编码方式不对应,无法找出字符串
file = open(path)
sum=0
 for line in file.readlines():
  #line = line.strip("\n")
   key = "解析渲染" 
   if key in line:
     s = re.findall('"TimeSpan":"([\d.]+)"', line)
     print "**************", line
     print "时间为:", s[-1]
     sum = sum + float(s[-1])
 file.close()
print "总时间为:", sum
input("123")

注:print file.read()时会出现IOError[error 0],未知原因

知识点扩展:python 读写文件,按行修改文件

>>> f = open(r'E:\python\somefile.txt','w')        打开文件,写模式
>>> f.write('this\nis no \nhailu')             写入三行话
17
>>> f.close()
>>> f = open(r'E:\python\somefile.txt','r')
>>> f.read()
'this\nis no \nhailu'                    查看一下
>>> f = open(r'E:\python\somefile.txt')
>>> lines = f.readlines()                  把每一行的内容变为集合lines 的一个元素
>>> f.close()
>>> lines[1] = "isn't a\n"                 给lines的第二个元素 重新赋值(改写了)
>>> f = open(r'E:\python\somefile.txt','w')
>>> f.writelines(lines)
>>> f.close()                         
>>   
改写后的文件打开就是这个样子
<pre name="code" class="python">this
isn't a
hailu

总结

上一篇:Python线性回归实战分析

栏    目:Python代码

下一篇:Python中List.count()方法的使用教程

本文标题:python按行读取文件并找出其中指定字符串

本文地址:http://www.codeinn.net/misctech/70795.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有