python - 向用户读取文档行(python)

标签 python

我正在尝试编写一个程序来向用户读取 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 parameter sizehint, 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/

相关文章:

python - [Odoo][v10] Formview 中 cron 中的 IndexError 一切正常

python - 从 Django 模型生成分层 JSON 树结构

python - 通过索引列表置换元组

python - 返回 Basequery 对象,而不是从 sqlalchemy query.filter 中返回模型对象

python - 如何对 django 消息进行单元测试?

python - 使用 Python 列出 FTP 中所有子目录中的所有文件

python:检测字符串中的负数

python - Django "ValueErrror: could not find common ancestor of {migrations}"

python - 如何使用 OCR 有效地从 PDF 文件目录中提取文本?

python - 如何检测圆形腐 eclipse /膨胀