Python 文本文件读取和打印数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17440815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:14:00  来源:igfitidea点击:

Text File Reading and Printing Data

pythonfilepython-2.7

提问by misguided

My Text File MyText.txt

我的文本文件 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

Objective

客观的

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)"

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

My Code

我的代码

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()

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.

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

采纳答案by vidit

This should work..

这应该工作..

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]

回答by mbdavis

Personally I'd get the text out, and then perform operations on it, if the file is fairly small.

如果文件相当小,我个人会取出文本,然后对其执行操作。

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])

回答by Ramakanth Reddy

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