Skip to main content
 首页 » 编程设计

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

2024年11月24日9txw1958

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.

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

writeline 和 writelines 同样的问题。

请您参考如下方法:

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