如何将CSV文件转换为JSON文件,使每列对应一个JSON列表?
问题分析与解决方案
你的代码存在两个核心问题:
pd.read_csv默认以逗号作为分隔符,但你的CSV文件是空格分隔,会导致读取的数据格式错误;df.to_json()默认输出的是「列名→{索引→值}」的嵌套字典结构,而非你需要的「列名→值列表」格式。
解决方案一:修正Pandas代码
直接利用to_dict('list')生成目标格式的字典,再写入JSON文件,同时指定正确的分隔符:
import pandas as pd import json def func(csvFilePath, jsonFilePath): # 指定sep='\s+'匹配多空格分隔 df = pd.read_csv(csvFilePath, sep='\s+') # 转换为列名对应值列表的字典 column_dict = df.to_dict('list') # 写入JSON文件并格式化缩进 with open(jsonFilePath, 'w', encoding='utf-8') as f: json.dump(column_dict, f, indent=2)
执行后生成的JSON文件完全符合你的预期格式。
解决方案二:纯Python实现(无Pandas依赖)
如果不想引入Pandas库,可直接读取文件逐行处理:
import json def func(csvFilePath, jsonFilePath): result = {} with open(csvFilePath, 'r', encoding='utf-8') as f: # 读取表头并初始化空列表 headers = f.readline().strip().split() for header in headers: result[header] = [] # 遍历数据行,填充对应列表 for line in f: line = line.strip() if not line: continue values = list(map(int, line.split())) for header, val in zip(headers, values): result[header].append(val) # 写入JSON文件 with open(jsonFilePath, 'w', encoding='utf-8') as f: json.dump(result, f, indent=2)
内容的提问来源于stack exchange,提问作者evening
相关产品推荐
相关产品推荐

