1. CSV 文件读写
读取和写入 CSV 文件,常用于数据表格处理。
import csv
# 读取 CSV 文件
with open('data.csv', newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
# 写入 CSV 文件
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 25])
writer.writerow(['Bob', 30])
广泛用于处理结构化数据,例如电子表格和数据库导出。
2. JSON 文件读写
读取和写入 JSON 格式的数据,适合存储复杂数据结构。
import json
# 写入 JSON 文件
data = {'name': 'Alice', 'age': 25}
with open('data.json', 'w', encoding='utf-8') as jsonfile:
json.dump(data, jsonfile)
# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as jsonfile:
data = json.load(jsonfile)
print(data)
常用于 API 数据交互和配置文件管理。