在 Python 中到达文件末尾时 readline 返回什么值? [英] What value does readline return when reaching the end of the file in Python?

查看:154
本文介绍了在 Python 中到达文件末尾时 readline 返回什么值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用经典循环

file_in = open('suppliers.txt', 'r')
line = file_in.readline()

while line:
    line = file_in.readline()

在 Python 中逐行读取文件.

to read through a file line-by-line in Python.

但是当循环退出时'line'有什么值?Python 3 文档仅读取:

But what value does 'line' have when the loop exits? The Python 3 docs only read:

readline(size=-1)

从流中读取并返回一行.如果指定了大小,则在将读取大部分 size 字节.

Read and return one line from the stream. If size is specified, at most size bytes will be read.

二进制文件的行终止符总是 b'\n';对于文本文件,open() 的换行参数可用于选择行已识别终止符.

The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

编辑:

在我的 Python 版本 (3.6.1) 中,如果您以二进制模式打开文件,help(file_in.readline) 给出

In my version of Python (3.6.1), if you open a file in binary mode, help(file_in.readline) gives

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.

这与上面引用的文档完全相同.但是,正如 Steve Barnes 所指出的,如果您以文本模式打开文件,您会得到有用的评论.(糟糕!我的复制粘贴错误)

which is exactly the same as the docs quoted above. But, as noted by Steve Barnes, if you open the file in text mode, you get a useful comment. (Oops! Copy-paste error on my part)

推荐答案

来自教程:https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects

f.readline() 从文件中读取一行;换行符(\n) 留在字符串的末尾,仅在如果文件不以换行符结尾,则为文件的最后一行.这使得返回值明确;如果 f.readline() 返回一个空的字符串,已到达文件末尾,而空行是由 '\n' 表示,一个只包含一个换行符的字符串.

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

这篇关于在 Python 中到达文件末尾时 readline 返回什么值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆