文本文件读取和打印数据

时间:2013-07-03 06:06:58

标签: python file python-2.7

我的文字档案MyText.txt

This is line 1
This is line 2 
Time Taken for writing this#      0 days 0 hrs 1 min 5 sec
Nothing Important
Sample Text

目标

读取文本文件并查找文件中是否存在“样品测试。如果存在,则打印写入文件所需的时间(文件中已存在的值)”

我的代码

with open('MyText.txt', 'r') as f:
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            f.seek(0)
            f.readline()
            for line in f:
                if 'Time Taken' in line:
                    print line
                    print ' '.join(line.split())
f.close()

代码运行正常。我的问题是,如果这个代码可以做得更好。考虑到我是python的新手,我相信会有更好的方法对此进行编码。任何人都可以为此提出替代/更快的方法。

3 个答案:

答案 0 :(得分:3)

f = open('sample', 'r') # open file in read mode
data = f.read()      # copy to a string
f.close()               # close the file
print data          # print the data

答案 1 :(得分:2)

就个人而言,如果文件很小,我会把文本拿出来然后对它进行操作。

f = open("mytext.txt","r")
contents = f.read()
f.close()

for row in contents.split("\n"):
    if "time" in row:
        print(row.split("time")[1])

答案 2 :(得分:0)

这应该有用..

with open('MyText.txt', 'r') as f:
  lineArr=f.read().split('\n')
  if 'Sample Text' in lineArr:
    timeTaken = [s for s in lineArr if "Time Taken" in s]
    print timeTaken[0]