如何获取python来读取.txt文件的第n行? [英] How can I get python to read every nth line of a .txt file?
问题描述
如果我想让python读取文件的第2行(或第4行),我如何告诉它这样做?另外,如果我想读取.txt文件的第2行,但之后每4行读取(下一行将是6行,然后是10行,依此类推),我该如何做呢?
If I wanted python to read every 2nd (or every 4th) line of a file, how could I tell it to do so? Additionally, if I wanted to read line 2 of a .txt file, but every 4 lines after that (next line would be line 6, then 10, and so on forth), how could I make it do so?
推荐答案
您不能... [使用纯I/O函数进行操作]您必须阅读所有行,并使代码仅忽略您所需要的行不需要.
You can't... [do it using pure I/O functions] You have to read all lines and simply make your code ignore the lines that you do not need.
例如:
with open(filename) as f:
lines = f.readlines()
desired_lines = lines[start:end:step]
在上面的代码中,将开始,结束和步骤替换为所需的值,例如"...如果我想读取.txt文件的第2行,但之后每4行..." 您会这样:
In the code above replace start, end, and step with desired values, e.g., "...if I wanted to read line 2 of a .txt file, but every 4 lines after that..." you would do like this:
desired_lines = lines[1::4]
这篇关于如何获取python来读取.txt文件的第n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!