with open('data.csv', mode='r') as file: reader = csv.reader(file) for row in reader: print(row) # 每一行是一个列表
写入CSV文件
利用csv.writer将数据写入CSV文件。
data = [ ['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'Los Angeles'],]with open('output.csv', mode='w', newline='') as file: writer = csv.writer(file) writer.writerows(data) # 写入多行
2. JSON文件操作导入JSON模块
import json
读取JSON文件
利用json.load()读取JSON文件的内容。
with open('data.json', mode='r') as file: data = json.load(file) print(data) # 读取的数据是字典或列表
写入JSON文件
利用json.dump()将数据写入JSON文件。

data = { 'employees': [ {'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'} ]}with open('output.json', mode='w') as file: json.dump(data, file, indent=4) # indent参数用于美化输出
3. 处理繁芜数据
对付包含嵌套构造的CSV或JSON,可以利用相应的处理方法。
读取繁芜CSV可以利用pandas库处理繁芜的CSV数据。
import pandas as pddf = pd.read_csv('complex_data.csv')print(df.head()) # 查看前5行
写入繁芜JSON
可以将嵌套字典或列表直接写入JSON。
nested_data = { 'departments': { 'HR': ['Alice', 'Bob'], 'Engineering': ['Charlie', 'David'] }}with open('nested_output.json', mode='w') as file: json.dump(nested_data, file, indent=4)
CSV和JSON是常用的数据交流格式,理解它们的读写操作是数据处理中的主要技能。