文件操作
学习Python的文件读写、遍历和CSV处理
45%
文件读写
文件遍历
二进制与CSV
练习例题
文件读写
读写文本文件
使用 open()
打开文本文件进行读取和写入。
# 读取文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 写入文件
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!')
- 文本模式下要指定合适的编码
- 写入模式('w')会覆盖已有内容,使用('a')可追加
- 用
with
上下文管理器确保文件自动关闭