在Python中的.txt文件中打印特定行? [英] Print specific line in a .txt file in Python?
本文介绍了在Python中的.txt文件中打印特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个.txt文件,其中包含很多行.我想让我的程序问我要打印哪一行,然后将其打印到python shell中. .txt文件称为packages.txt.
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.
推荐答案
如果您不想预先读取整个文件,则可以简单地进行迭代,直到找到行号为止:
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
或者您也可以使用itertools.islice()
切出所需的行(这有点hacky)
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
这篇关于在Python中的.txt文件中打印特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文