Python 文件处理
本文整理了 Python 中的各种文件处理操作:打开文件、读取文件内容、创建文件、写入文件、删除文件、删除文件夹。
文件处理是任何应用程序的重要组成部分。Python 提供了用于创建、读取、写入和删除文件(夹)的方法。
打开文件
在 Python 中 open()
函数用于打开一个文件并返回文件对象。 open()
函数是一个全局函数,可以随时随地使用它。
open(file, mode)
函数接受两个参数: file
和 mode
。
-
file
表示将要打开的文件的路径(绝对路径或者当前工作目录的相对路径),也可以是要被封装的整数类型文件描述符。 -
mode
是可选的,用于指定打开文件的模式,默认值是 ‘r’。可用的模式包括:'r'
- 读取,默认值。打开一个文件进行读取,如果文件不存在则报错'a'
- 追加,打开一个文件在文件尾部追加内容,如果文件不存在则创建该文件'w'
- 写入,打开一个文件进行写入,如果文件不存在则创建该文件'x'
- 创建,创建指定的文件,如果文件存在则返回错误't'
- 文本模式,默认值。'b'
- 二进制模式(例如图像)'+'
- 打开用于更新(读取与写入)
默认模式
'r'
与'rt'
相同,用于读取文本。
要打开文件进行读取,指定文件名就足够了:
f = open('demofile.txt')
上面的代码是一样的:
f = open('demofile.txt', 'rt')
因为 'r'
和 't'
是默认值,所以不需要指定它们。
如果文件不存在,会抛出一个错误:
>>> f = open('demofile.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'demofile.txt'
读取文件
假设我们有以下文件 demofile.txt,位于与 python 文件相同的文件夹中。
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
要读取文件的内容,可以使用文件对象的 read()
方法 和 readLine()
方法。
读取全部内容
打开并读取文件:
f = open('demofile.txt', 'r')
print(f.read())
如果文件位于不同的位置,则必须指定文件路径,如下所示:
f = open('D:\myfiles\welcome.txt', 'r')
print(f.read())
读取部分内容
默认情况下,文件对象的 read()
方法读取整个文件的内容,但您也可以指定要返回的字符数。
返回文件的前 5 个字符:
f = open('demofile.txt', 'r')
print(f.read(5)) # Hello
读取一行内容
文件对象的 readline()
方法读取一行文件内容。
读取文件的一行:
f = open('demofile.txt', 'r')
print(f.readline()) # Hello! Welcome to demofile.txt
通过调用 readline()
两次,您可以阅读前两行:
读取文件的两行:
f = open('demofile.txt', 'r')
print(f.readline()) # Hello! Welcome to demofile.txt
print(f.readline()) # This file is for testing purposes.
循环遍历文件行
文件对象是一个可迭代对象,可以通过 for
循环遍历文件的各行。
f = open('demofile.txt', 'r')
for x in f:
print(x)
关闭文件
文件对象的 close()
方法用于关闭文件。完成文件处理后始终关闭文件是一种很好的习惯。
f = open('demofile.txt', 'r')
print(f.readline())
f.close()
! 注意: 您应该始终关闭您的文件,在某些情况下,由于缓存,对文件所做的更改可能在您关闭文件后才会显示。
写入现有文件
要写入现有文件,您必须向 open()
函数传入 mode
参数,有 2 个模式可用于写入文件:
'a'
- 附加 - 将附加到文件的末尾,如果文件不存在则创建文件'w'
- 写入 - 将覆盖任何现有内容,如果文件不存在则创建文件
打开文件 “demofile2.txt” 并将内容追加到文件中:
f = open('demofile2.txt', 'a')
f.write('Now the file has more content!')
f.close()
#
f = open('demofile2.txt', 'r')
print(f.read()) # Now the file has more content!
打开文件 “demofile3.txt” 并覆盖内容:
f = open('demofile3.txt', 'w')
f.write('Woops! I have deleted the content!')
f.close()
#open and read the file after the appending:
f = open('demofile3.txt', 'r')
print(f.read()) # Woops! I have deleted the content!
!! 注意: 'w'
模式将覆盖整个文件。
创建新文件
要创建新文件,您必须向 open()
函数传入 mode
参数,有 3 个模式可以创建新文件:
'x'
- 创建,将创建一个文件,如果文件存在则返回错误'a'
- 附加,如果指定的文件不存在,将创建一个文件'w'
- 写入,如果指定的文件不存在,将创建一个文件
创建一个名为 “myfile.txt” 的文件:
f = open('myfile.txt', 'x')
结果:创建了一个新的空文件!
当使用 'x'
模式时,如果文件存在,则会抛出一个 FileExistsError
错误。
我们继续创建刚刚创建过的文件试一下。
>>> f = open('myfile.txt', 'x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'myfile.txt'
删除文件
要删除文件,您必须导入 os
模块,通过 os.remove()
方法删除文件。
import os
os.remove('myfile.txt')
如果删除的文件不存在,则会抛出一个 FileNotFoundError
错误:
>>> import os
>>> os.remove('myfile.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'myfile.txt'
为避免出现错误,您可能需要在尝试删除文件之前检查该文件是否存在:
检查文件是否存在,然后删除它:
import os
if os.path.exists('myfile.txt'):
os.remove('myfile.txt')
else:
print('The file does not exist')
删除文件夹
os.rmdir()
方法可用于删除文件夹。 os.rmdir()
只能用于删除空文件夹,如果文件夹中包含文件,需要先删除删除文件,再删除文件夹。
import os
os.rmdir('myfolder')