📝 文件IO
markmap 思维导图(可用于 markmap 工具)
📂 打开文件
Python 通过内置的 open()
函数来进行文件操作。常用的模式有:
"r"
:只读模式(默认)"w"
:写入模式,会创建文件(如果不存在),覆盖原有内容"a"
:追加模式,在文件末尾追加内容(如果文件存在)"x"
:独占创建模式,只能用于新建文件,若文件已存在则报错(Python 3.3+ 支持)"b"
:二进制模式(可与其他模式组合,如"rb"
、"wb"
)
'''1. 打开文件,并手动关闭'''
file = open('test.txt', 'r')
print(file.read())
file.close()
'''2. 使用 with 关键字,with语句会自动关闭文件'''
with open('test.txt', 'r') as file:
print(file.read())
⚡ 重点:推荐使用
with
语句管理文件,能自动关闭文件,避免资源泄漏。
📄 文件读取
读取文本文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
按行读取
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
注意:
line.strip()
可以去除每行末尾的换行符。
file.read()
读取整个文件的内容。file.readline()
读取文件的一行内容。file.readlines()
读取文件所有行,返回一个包含行内容的列表。
✍️ 文件写入与追加
写入文本文件
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!\n')
f.write('文件写入示例。')
追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write('\n追加内容。')
创建新文件,并写入(如果文件已存在则报错)
with open('output.txt', 'x', encoding='utf-8') as f:
f.write('新内容。')
🧊 二进制文件操作
二进制文件常用于图片、音频、视频等非文本数据的读写。
1. 读取二进制文件
with open('image.png', 'rb') as f:
data = f.read()
print(data[:20]) # 打印前20个字节
重点:'rb'
模式读取到的是 bytes
类型数据。
2. 写入二进制文件
with open('text.txt', 'wb') as f:
f.write(b"hello")
重点:'wb'
模式写入的内容必须是 bytes
类型。
3. 追加二进制内容
with open('data.bin', 'ab') as f:
f.write(b"more data")
重点:'ab'
模式用于二进制追加写入。
4. 二进制内容的转码与解码
- 编码(encode):字符串 → 二进制
- 解码(decode):二进制 → 字符串
text = "你好,Python!"
# 编码
binary_data = text.encode('utf-8')
print(binary_data) # b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cPython\xef\xbc\x81'
# 解码
decoded_text = binary_data.decode('utf-8')
print(decoded_text) # 你好,Python!
🛡️ 异常处理示例
文件操作时常见异常如 FileNotFoundError
,可以用 try-except 捕获:
try:
with open('nofile.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("文件不存在!")