Print specific line in a .txt file in Python?

自闭症网瘾萝莉.ら 提交于 2020-02-03 01:26:07

问题


I have got a .txt file that contains a lot of lines. I would like my program to ask me what line I would like to print and then print it into the python shell. The .txt file is called packages.txt.


回答1:


If you don't want to read in the entire file upfront, you could simply iterate until you find the line number:

with open('packages.txt') as f:
    for i, line in enumerate(f, 1):
        if i == num:
            break
print line

Or you could use itertools.islice() to slice out the desired line (this is slightly hacky)

with open('packages.txt') as f:
    for line in itertools.islice(f, num+1, num+2):
        print line



回答2:


If the file is big, using readlines is probably not a great idea, it might be better to read them one by one until you get there.

line_number = int(raw_input('Enter the line number: '))
with open('packages.txt') as f:
    i = 1
    for line in f:
        if i == line_number:
            break
        i += 1
    # line now holds the line 
    # (or is empty if the file is smaller than that number)
    print line

(Updated to fix the mistake in the code)




回答3:


How to refer to a specific line of a file using line number ? as in java if line number = i and file is stored in f then f(i) would do.



来源:https://stackoverflow.com/questions/10467913/print-specific-line-in-a-txt-file-in-python

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