Python read text file from second line to fifteenth [closed]

戏子无情 提交于 2019-11-29 08:14:41

问题


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!


回答1:


Use itertools.islice:

from itertools import islice
with open('filename') as fin:
    for line in islice(fin, 1, 16):
        print line



回答2:


If the file isn't very big:

with open('/path/to/file') as f:
    print f.readlines()[1:15]



回答3:


Jon's answer is definitely a more pythonic and clean approach.


Alternatively, you can use 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:

with open("file", 'r') as f:
    for i, x in enumerate(f):
        if 1 <= i <= 15:
            print x
        elif i > 15:
            break



回答4:


I think you can just read the lines and take the ones you need

For example:

file = open("a.txt", "r")
data = file.readlines()

now data[1] will be second line and data[14] will be 15th

You can put them into a variable and that's it



来源:https://stackoverflow.com/questions/18422127/python-read-text-file-from-second-line-to-fifteenth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!