Python从第二行到第十五行读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18422127/
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
Python read text file from second line to fifteenth
提问by Den1al
I have a text file and I need to read from the seconds line to to 15th line including. I've tried some methods but no method worked for me... I'd be happy if anyone could help me ... thanks a lot!
我有一个文本文件,我需要从秒行读取到第 15 行,包括。我尝试了一些方法,但没有任何方法对我有用...如果有人能帮助我,我会很高兴...非常感谢!
采纳答案by Jon Clements
Use itertools.islice
:
使用itertools.islice
:
from itertools import islice
with open('filename') as fin:
for line in islice(fin, 1, 16):
print line
回答by Jon Clements
If the file isn't very big:
如果文件不是很大:
with open('/path/to/file') as f:
print f.readlines()[1:15]
回答by alecxe
Jon's answeris definitely a more pythonic and clean approach.
乔恩的回答绝对是一种更加 Pythonic 和干净的方法。
Alternatively, you can use enumerate()
:
或者,您可以使用enumerate()
:
with open("file", 'r') as f:
print [x for i, x in enumerate(f) if 1 <= i <= 15]
Note, that this will loop over all lines in a file. It's better to break the loop after the 15th line, like this:
请注意,这将遍历文件中的所有行。最好在第 15 行之后中断循环,如下所示:
with open("file", 'r') as f:
for i, x in enumerate(f):
if 1 <= i <= 15:
print x
elif i > 15:
break
回答by Ofek .T.
I think you can just read the lines and take the ones you need
我认为你可以阅读这些行并选择你需要的
For example:
例如:
with open("a.txt", "r") as text_file:
data = text_file.readlines()
now data[1]
will be second line and data[14]
will be 15th, so you can slice it as such data[1:14]
现在data[1]
将是第二行并且data[14]
将是第 15 行,因此您可以将其切片data[1:14]
Then you can put them into a variable and that's it
然后你可以把它们放到一个变量中,就是这样