文本文件读取和打印数据 [英] Text File Reading and Printing Data
本文介绍了文本文件读取和打印数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的文本文件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
客观
要读取文本文件并查找文件中是否存在样本测试.如果存在,则打印写入文件所花费的时间(这是文件中已经存在的值)"
To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file(which is a value already inside the file)"
我的代码
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的新手,我相信会有更好的方法来编写此代码.任何人都可以建议使用其他/更快的方法.
The code is working fine. My question is if this code can be made even better . Considering I am new to python, I am sure there would be a better way to code this.Can anyone sugggest alternative/faster approach for this.
推荐答案
这应该有效.
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]
这篇关于文本文件读取和打印数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文