简体   繁体   English

在Python中的.txt文件中打印特定行?

[英]Print specific line in a .txt file in Python?

I have got a .txt file that contains a lot of lines. 我有一个.txt文件,其中包含很多行。 I would like my program to ask me what line I would like to print and then print it into the python shell. 我想让我的程序问我要打印哪一行,然后将其打印到python shell中。 The .txt file is called packages.txt. .txt文件称为packages.txt。

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) 或者,您可以使用itertools.islice()切出所需的行(这有点hacky)

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

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. 如果文件很大,那么使用readlines可能不是一个好主意,最好逐个读取它们,直到到达为止。

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) (已更新,以修复代码中的错误)

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. 如在Java中,如果行号= i并且文件存储在f中,则f(i)会这样做。

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

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