主题
读写文本文件
在实际开发中,处理文件是一项非常常见的任务。Python 提供了内置的 open()
函数用于文件的读取与写入操作,支持多种模式与编码方式。
打开文件
使用 open()
函数可以打开一个文件并返回文件对象。
python
# 以读取模式打开文件
f = open('example.txt', 'r', encoding='utf-8')
常见模式包括:
模式 | 含义 |
---|---|
'r' | 只读模式(默认) |
'w' | 写入模式(覆盖原文件) |
'a' | 追加模式 |
'x' | 创建新文件写入 |
'b' | 二进制模式 |
't' | 文本模式(默认) |
读取文件内容
python
f = open('example.txt', 'r', encoding='utf-8')
content = f.read()
print(content)
f.close()
也可以逐行读取:
python
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
写入文件
使用写入或追加模式写入文件内容:
python
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Hello, Python!\n")
f.write("这是第二行文本。")
如果使用 'a'
模式,则会在文件末尾追加内容:
python
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("\n追加的新行。")
推荐的 with
语法
with open(...) as f
是推荐的写法,能够自动管理资源,文件使用后自动关闭。
python
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
文件不存在或权限问题
读取文件时可能出现异常,建议使用 try-except
结构进行处理:
python
try:
with open('nonexistent.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("文件未找到!")
except IOError:
print("文件读取错误!")
总结
- 使用
open()
函数读写文件,建议配合with
语句; - 熟悉各种打开模式,按需使用
'r'
、'w'
、'a'
等; - 注意处理文件不存在或编码错误等异常;
- 善于拆解文件操作任务,提高代码健壮性。