首页 » PHP教程 » phpcsv读写技巧_Python CSVJSON文件读写操作

phpcsv读写技巧_Python CSVJSON文件读写操作

访客 2024-12-09 0

扫一扫用手机浏览

文章目录 [+]

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文件的内容。

phpcsv读写技巧_Python CSVJSON文件读写操作

with open('data.json', mode='r') as file: data = json.load(file) print(data) # 读取的数据是字典或列表写入JSON文件

利用json.dump()将数据写入JSON文件。

phpcsv读写技巧_Python CSVJSON文件读写操作
(图片来自网络侵删)

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是常用的数据交流格式,理解它们的读写操作是数据处理中的主要技能。

标签:

相关文章