【发布时间】:2017-12-14 14:47:38
【问题描述】:
可以使用经典循环
file_in = open('suppliers.txt', 'r')
line = file_in.readline()
while line:
line = file_in.readline()
在 Python 中逐行读取文件。
但是当循环退出时,'line' 有什么值呢? Python 3 文档仅阅读:
readline(size=-1)
从流中读取并返回一行。如果指定了大小,则在 大多数 size 字节将被读取。
对于二进制文件,行终止符总是 b'\n';对于文本文件, open() 的换行参数可用于选择行 已识别终止符。
编辑:
在我的 Python 版本(3.6.1)中,如果你以二进制模式打开文件,help(file_in.readline) 给出
readline(size=-1, /) method of _io.BufferedReader instance
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text
files, the newlines argument to open can be used to select the line
terminator(s) recognized.
与docs quoted above 完全相同。但是,正如Steve Barnes 所指出的,如果您以文本模式打开文件,您会得到一个有用的注释。 (糟糕!我的复制粘贴错误)
【问题讨论】:
-
过去的文档更容易理解。
-
TextIOBase记录readline在 EOF 上返回一个空字符串;以上摘自IOBase中的描述。