0Pricing
Python Academy · 课时

使用 with 语句处理文件

使用上下文管理器确保文件自动关闭。

使用 with 语句处理文件 是 CoddyKit 上的免费 Python Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。

介绍

with 语句可确保文件自动关闭,即使发生异常也是如此。

with 语句

with open('file.txt') as f: ... 会在代码块退出时自动关闭 f,无论是正常退出还是因异常退出。
# with open('data.txt') as f:
#     content = f.read()
# f is now closed
print('with demo')

为什么 with 优于 try/finally

如果不使用 with,您必须编写 try: ... finally: f.close() 来确保文件关闭。with 会自动处理这一点。
# Equivalent to:
# f = open('file.txt')
# try:
#     content = f.read()
# finally:
#     f.close()
print('comparison demo')

多个文件

with open('a.txt') as a, open('b.txt') as b: 可以在一条语句中打开两个文件。
# with open('in.txt') as src, open('out.txt','w') as dst:
#     for line in src:
#         dst.write(line.upper())
print('multi-file demo')

上下文管理器协议

with 使用 __enter__ 和 __exit__。open() 返回的文件对象实现了这两个方法。稍后我们会编写自己的上下文管理器。
# f.__enter__() opens
# f.__exit__() closes
print('protocol demo')

读取和处理

将 with、for line in f: 和 .strip() 结合起来,可以干净地处理每一行:去除换行符并跳过空行。
lines = ['  hello  \n', '  world  \n']
cleaned = [l.strip() for l in lines if l.strip()]
print(cleaned)

使用 with 写入

with open('out.txt','w') as f: f.write('data')——离开代码块时,文件会被刷新并关闭。
# with open('out.txt', 'w') as f:
#     for i in range(10):
#         f.write(f'{i}\n')
print('write with demo')

检查文件是否存在

import os; os.path.exists('file.txt') 会在文件存在时返回 True。这样可以避免 FileNotFoundError。
import os
print(os.path.exists('/tmp'))
print(os.path.exists('/nonexistent'))

open() 错误

FileNotFoundError:文件不存在。PermissionError:没有读取或写入权限。请使用 try/except 进行稳健处理。
try:
    with open('/nonexistent.txt') as f:
        pass
except FileNotFoundError as e:
    print('File not found:', e)

用于内存中文件的 StringIO

from io import StringIO 可以让您将字符串用作文件对象,非常适合测试文件处理代码。
from io import StringIO
buf = StringIO('line1\nline2\n')
for line in buf:
    print(line.rstrip())

tempfile 模块

tempfile.NamedTemporaryFile() 会创建一个在关闭时删除的临时文件。它适合安全地处理临时数据。
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=True) as f:
    f.write('temp data')
    print(f.name)

快速检查

将 with 语句用于文件输入输出时,它能保证什么?

回顾

with open(f) as h: 会自动关闭 h。处理多个文件时使用多个目标。使用 StringIO 进行内存中的测试。请妥善处理 FileNotFoundError。

继续学习

做得很好!请继续下一课,持续进步。

常见问题解答

「使用 with 语句处理文件」课时是免费的吗?

是的 — 「使用 with 语句处理文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。

「使用 with 语句处理文件」这节课中我会学到什么?

使用上下文管理器确保文件自动关闭。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 with 语句处理文件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python Academy 课中编写并运行代码吗?

能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 打开与读取文件
  2. 写入文件与追加内容
  3. 使用 with 语句处理文件
  4. 使用 pathlib 处理文件路径
← 返回 Python Academy