【问题标题】:Do `readline`, `readlines`, `writeline` and `writelines` require `file` object `f` to be opened in text mode not binary mode?`readline`、`readlines`、`writeline` 和 `writelines` 是否需要以文本模式而不是二进制模式打开 `file` 对象 `f`?
【发布时间】:2019-05-29 11:47:08
【问题描述】:

根据 Python in a Nutshell,Afileobject f 具有以下 IO 方法:

f.read(size=-1)

在 v2 或 v3 中当 f 以二进制模式打开时,读取最多为 size f 的文件中的字节并将它们作为字节串返回。读读和 如果文件在 size 字节之前结束,则返回小于 size 字节 读。当 size 小于 0 时, read 读取并返回所有字节,直到 文件的结尾。当文件的 read 返回一个空字符串 当前位置位于文件末尾或大小等于 0 时。在 v3,当f在文本模式下打开时,size是字符数,不是 字节,读取返回一个文本字符串。

f.readline(size=-1)

从 f 的文件中读取并返回一行,直到行尾 (\n), 包括。当size大于等于0时,readline读取no 超过 size 个字节。在这种情况下,返回的字符串可能不会结束 与\n。当 readline 读到结尾时,\n 也可能不存在 没有找到\n的文件。 readline 时返回一个空字符串 文件的当前位置在文件末尾或大小时 等于 0。

f.readlines(size=-1)

读取并返回 f 文件中所有行的列表,每行都是一个字符串 以 \n 结尾。如果 size>0,readlines 停止并在之后返回列表 收集总共大约 size 个字节的数据,而不是读取 一直到文件末尾;在这种情况下,最后一个字符串 列表可能不会以 \n 结尾。

readlinereadlines 是否要求 file 对象 f 以文本模式而不是二进制模式打开?

writelinewritelines 的问题相同。

【问题讨论】:

  • 没有writeline。应该明确添加\n(就像writelines一样)。

标签: python python-3.x


【解决方案1】:

不,它们也以二进制模式工作,在 b'\n' 上拆分,并返回 bytes 对象列表。

用 Python 3.5.2 试过,得到这个输出:

[14:52:44]adamer8:~ ()$ cat Sample.txt
country
code
bold
hello
yellow
country
code
bold
country
[14:52:48]adamer8:~ ()$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','rb')
>>> content = f.readlines()
>>> print(content)
[b'country\n', b'code\n', b'bold\n', b'hello\n', b'yellow\n', b'country\n', b'code\n', b'bold\n', b'country\n']
>>> type(content[0])
<class 'bytes'>
>>> 

当使用 'r' 模式打开文件时,我们会得到字符串:

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('Sample.txt','r')
>>> content = f.readlines()
>>> print(content)
['country\n', 'code\n', 'bold\n', 'hello\n', 'yellow\n', 'country\n', 'code\n', 'bold\n', 'country\n']
>>> type(content[0])
<class 'str'>
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多