我正在尝试编写一个程序来向用户读取 5 行文本文档,但我无法让它工作。它当前打印第 4 行和第 5 行以及每个行的“\n”(新行)。这是代码:
filename = 'text_file_example.txt'
myfile = open(filename,'r')
myfile.readlines(5)
print(myfile.readlines(5))
myfile.close()
在 for(range 5) 循环中读取一行会更好吗?
最佳答案
您正在使用的内置函数 readlines()
执行以下操作 ( from the official documentation ):
f.readlines()
returns a list containing all the lines of data in the file. If given an optional parametersizehint
, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that.
也许您可能想这样做:
filename = 'text_file_example.txt'
myfile = open(filename,'r')
file_lines = myfile.readlines()
for line in file_lines[:5]:
print(line)
myfile.close()
关于python - 向用户读取文档行(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13988421/