gpt4 book ai didi

python - `readline` 、 `readlines` 、 `writeline` 和 `writelines` 是否需要 `file` 对象 `f` 以文本模式而不是二进制模式打开?

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:32 24 4
gpt4 key购买 nike

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

f.read(size=-1)

In v2, or in v3 when f is open in binary mode, read reads up to size bytes from f’s file and returns them as a bytestring. read reads and returns less than size bytes if the file ends before size bytes are read. When size is less than 0, read reads and returns all bytes up to the end of the file. read returns an empty string when the file’s current position is at the end of the file or when size equals 0. In v3, when f is open in text mode, size is a number of characters, not bytes, and read returns a text string.

f.readline(size=-1)

Reads and returns one line from f’s file, up to the end of line (\n), included. When size is greater than or equal to 0, readline reads no more than size bytes. In that case, the returned string might not end with \n. \n might also be absent when readline reads up to the end of the file without finding \n. readline returns an empty string when the file’s current position is at the end of the file or when size equals 0.

f.readlines(size=-1)

Reads and returns a list of all lines in f’s file, each a string ending in \n. If size>0, readlines stops and returns the list after collecting data for a total of about size bytes rather than reading all the way to the end of the file; in that case, the last string in the list might not end in \n.

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

writelinewritelines 同样的问题。

最佳答案

不,它们也以二进制模式工作,在 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'>
>>>

关于python - `readline` 、 `readlines` 、 `writeline` 和 `writelines` 是否需要 `file` 对象 `f` 以文本模式而不是二进制模式打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com