简体   繁体   English

如何从python中的.txt文件读取特定行?

[英]How to read one particular line from .txt file in python?

I know I can read the line by line with 我知道我可以逐行阅读

dataFile = open('myfile.txt', 'r')
firstLine = dataFile.readline()
secondLine = dataFile.readline()
...

I also know how to read all the lines in one go 我也知道如何一次阅读所有行

dataFile = open('myfile.txt', 'r')
allLines =  dataFile.read()

But my question is how to read one particular line from .txt file? 但是我的问题是如何从.txt文件中读取某一行?

I wish to read that line by its index. 我希望按其索引阅读该行。

eg I want the 4th line, I expect something like 例如,我想要第四行,我期望像

dataFile = open('myfile.txt', 'r')
allLines =  dataFile.readLineByIndex(3)

Skip 3 lines: 跳过3行:

with open('myfile.txt', 'r') as dataFile:
    for i in range(3):
        next(dataFile)
    the_4th_line = next(dataFile)

Or use linecache.getline : 或使用linecache.getline

the_4th_line = linecache.getline('myfile.txt', 4)

From another Ans 从另一个Ans

Use Python Standard Library's linecache module:

line = linecache.getline(thefilename, 33)
should do exactly what you want. You don't even need to open the file -- linecache does it all for you!

You can do exactly as you wanted with this: 您可以完全按照自己的意愿进行操作:

DataFile = open('mytext.txt', 'r')

content = DataFile.readlines()

oneline = content[5]

DataFile.close()

you could take this down to three lines by removing oneline = content[5] and using content[5] without creating another variable ( print(content[5]) for example) I did this just to make it clear that content[5] must be a used as a list to read the one line. 您可以通过删除oneline = content[5]并使用content[5]而无需创建另一个变量(例如, print(content[5])将其减少到三行,我这样做只是为了明确content[5] 必须用作读取单行的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM