菜单
本页目录

1. with基本语法

with open('file_path', 'mode', encoding='encoding_type') as file:
    # 对文件进行操作的代码块
    pass

其中:
open('file_path', 'mode', encoding='encoding_type')用于打开指定路径的文件,
'mode'是文件打开模式(如 'r' 只读、'w' 写入、'a' 追加等),
'encoding_type' 是文件编码(如 'utf-8')。
as file将打开的文件对象赋值给变量 file,
在 with 语句块内可以使用这个变量对文件进行操作。

2. 工作原理

with 语句利用了上下文管理器协议。
open() 函数返回的文件对象实现了 enter() 和 exit() 这两个特殊方法:
enter() 方法:当执行到 with 语句时,会自动调用文件对象的 enter() 方法,该方法返回文件对象本身(通常情况),并将其赋值给 as 后面的变量(如上述的 file)。
exit() 方法:当 with 语句块内的代码执行完毕,或者代码块内发生异常时,会自动调用文件对象的 exit() 方法。在 exit() 方法中,会进行文件关闭等资源清理操作,确保文件资源被正确释放。

3. 实例用法

3.1 文件读取

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

在这个例子中,with 语句打开 example.txt 文件,以只读模式('r')和 utf-8 编码。在 with 语句块内,使用 file.read() 方法读取整个文件内容并存储在 content 变量中,最后打印出来。当代码块执行完毕,文件会自动关闭,无需手动调用 file.close()。

3.2 文件写入

data = "这是要写入文件的内容。"
with open('new_file.txt', 'w', encoding='utf-8') as file:
    file.write(data)

这里以写入模式('w')打开 new_file.txt 文件。如果文件不存在,会创建新文件;如果文件已存在,会清空原有内容。在 with 语句块内,使用 file.write() 方法将字符串 data 写入文件。执行完代码块后,文件自动关闭。

3.3 文件追加

new_data = "追加到文件末尾的内容。"
with open('existing_file.txt', 'a', encoding='utf-8') as file:
    file.write(new_data)

使用追加模式('a')打开 existing_file.txt 文件。在 with 语句块内,使用 file.write() 方法将 new_data 追加到文件末尾。同样,代码块结束后文件自动关闭。

3.4 异常处理

with 语句在处理文件操作时,即使代码块内发生异常,也能确保文件被正确关闭。

try:
    with open('nonexistent_file.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        # 模拟一个可能出现的异常
        result = 1 / 0
        print(content)
except FileNotFoundError:
    print("文件未找到。")
except ZeroDivisionError:
    print("发生除零错误,但文件已正确关闭。")

在这个例子中,尝试打开一个不存在的文件可能会引发 FileNotFoundError 异常;在读取文件内容后,模拟了一个除零操作,会引发 ZeroDivisionError 异常。无论哪种异常发生,with 语句都会确保文件对象的 exit() 方法被调用,从而关闭文件。

3.5 同时操作多个文件

with 语句可以嵌套使用,方便同时对多个文件进行操作。

with open('input.txt', 'r', encoding='utf-8') as infile:
    with open('output.txt', 'w', encoding='utf-8') as outfile:
        content = infile.read()
        outfile.write(content.upper())

上述代码中,外层 with 语句以只读模式打开 input.txt 文件,内层 with 语句以写入模式打开 output.txt 文件。将 input.txt 文件的内容读取出来,转换为大写后写入 output.txt 文件。当内层 with 语句块执行完毕,output.txt 文件会自动关闭;当外层 with 语句块执行完毕,input.txt 文件会自动关闭。