文件操作
Python 提供了丰富的文件操作功能,可以轻松地读取和写入文件。
读取文件
# 方法1:使用 with 语句(推荐)
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read() # 读取整个文件
print(content)
# 方法2:逐行读取
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) # strip() 去除换行符
# 方法3:读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
print(lines)
写入文件
# 写入文本(覆盖模式)
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, Python!\n")
file.write("这是第二行\n")
# 追加模式
with open('output.txt', 'a', encoding='utf-8') as file:
file.write("这是追加的内容\n")
# 写入多行
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open('output.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
JSON 文件处理
import json
# 写入 JSON 文件
data = {
"name": "张三",
"age": 25,
"hobbies": ["阅读", "编程", "旅行"]
}
with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=2)
# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
print(loaded_data)
💡 提示:使用 with 语句可以自动关闭文件,避免资源泄漏。