Python 文件 I/O - 读取和写入文件
2023-09-17 22:15:37
在 Python 中,IO 模块提供了三种类型的 IO 操作的方法:原始二进制文件、缓冲二进制文件和文本文件。创建文件对象的规范方法是使用 open()
函数。
任何文件操作都可以通过以下三个步骤执行:
- 打开文件以使用内置open()函数获取文件对象。有不同的访问模式,您可以在使用 open() function 打开文件时指定这些模式。
- 使用从
open()
函数检索的文件对象执行读取、写入、追加操作。 - 关闭并释放文件对象。
读取文件(Reading File)
File 对象包括以下从文件中读取数据的方法。
- read(chars):从当前位置开始读取指定数量的字符。
- readline():读取从当前读取位置到换行符的字符。
- readlines():读取所有行,直到文件末尾并返回一个列表对象。
以下C:myfile.txt
文件将用于读取和写入文件的所有示例中。
This is the first line.
This is the second line.
This is the third line.
下面的示例使用 read(chars)
方法执行读取操作。
f = open('C:myfile.txt') # opening a file
lines = f.read() # reading a file
print(lines) #'This is the first line. nThis is the second line.nThis is the third line.'
f.close() # closing file object
上面,f = open('C:myfile.txt')
从当前目录以默认读取模式打开myfile.txt
并返回一个 file object 。
f.read()
函数以字符串形式读取所有内容,直到 EOF。如果在 read(chars)
方法中指定 char size 参数,则它只会读取那么多字符。
f.close()
将冲洗并关闭流。
读一行
下面的示例演示如何从文件中读取一行。
f = open('C:myfile.txt') # opening a file
line1 = f.readline() # reading a line
print(line1) #'This is the first line. n'
line2 = f.readline() # reading a line
print(line2) #'This is the second line.n'
line3 = f.readline() # reading a line
print(line3) #'This is the third line.'
line4 = f.readline() # reading a line
print(line4) #''
f.close() # closing file object
如您所见,我们必须以'r'
模式打开文件。readline()
方法将返回第一行,然后指向文件中的第二行。
读取所有行
下面使用 readlines()
函数读取所有行。
f = open('C:myfile.txt') # opening a file
lines = f.readlines() # reading all lines
print(lines) #'This is the first line. nThis is the second line.nThis is the third line.'
f.close() # closing file object
文件对象具有内置迭代器。以下程序逐行读取给定的文件,直到引发StopIteration
,即达到EOF。
f=open('C:myfile.txt')
while True:
try:
line=next(f)
print(line)
except StopIteration:
break
f.close()
使用 for 循环轻松读取文件。
f=open('C:myfile.txt')
for line in f:
print(line)
f.close()
输出:
This is the first line.
This is the second line.
This is the third line.
读取二进制文件(Reading Binary File)
使用 open()
函数中的"rb"模式读取二进制文件,如下所示。
f = open('C:myimg.png', 'rb') # opening a binary file
content = f.read() # reading all lines
print(content) #print content
f.close() # closing file object
写入文件(Writing to a File)
文件对象提供以下方法来写入文件。
- write(s):将字符串 s 写入流并返回写入的字符数。
- 写行(行):将行列表写入流。每行的末尾必须有一个分隔符。
创建新文件并写入
如果文件不存在或覆盖现有文件,则以下内容将创建一个新文件。
f = open('C:myfile.txt','w')
f.write("Hello") # writing to file
f.close()
# reading file
f = open('C:myfile.txt','r')
f.read() #'Hello'
f.close()
在上面的示例中,f=open("myfile.txt","w")
语句以写入模式打开myfile.txt
,open()
方法返回 file 对象并将其分配给变量 f
。
'w'
指定文件应该是可写的。
接下来,f.write("Hello")
覆盖myfile.txt
文件的现有内容。它返回写入文件的字符数,在上面的示例中为 5。
最后,f.close()
关闭文件对象。
追加到现有文件(Appending to an Existing File)
下面通过在 open()
方法中传递'a'
或'a+'
模式,将内容追加到现有文件的末尾。
f = open('C:myfile.txt','a')
f.write(" World!")
f.close()
# reading file
f = open('C:myfile.txt','r')
f.read() #'Hello World!'
f.close()
写入多行(Write Multiple Lines)
Python 提供了将列表对象的内容保存在文件中的writelines()
方法。
由于换行符不会自动写入文件,因此必须将其作为字符串的一部分提供。
lines=["Hello world.n", "Welcome to python114.com.n"]
f=open("D:myfile.txt", "w")
f.writelines(lines)
f.close()
打开具有"w"模式或"a"模式的文件只能写入,不能从中读取。同样,"r"模式只允许读取而不写入。 要同时执行读取/追加操作,请使用"a+"模式。
写入二进制文件(Writing to a Binary File)
默认情况下,open()
函数以文本格式打开文件。要打开二进制格式的文件,请将'b'
添加到 mode 参数。
因此,"rb"
模式以二进制格式打开文件进行读取,而"wb"
模式以二进制格式打开文件进行写入。与文本文件不同,二进制文件不是人类可读的。使用任何文本编辑器打开时,数据都无法识别。
下面的代码将数字列表存储在二进制文件中。在写入之前,首先将列表转换为字节数组。内置函数bytearray()返回对象的字节表示形式。
f=open("binfile.bin","wb")
num=[5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()
本文内容总结: