Python中如何通过config.json读取指定CSV文件的内容?
正确实现方法
你的问题出在没有解析JSON结构,只是把JSON文件内容当成普通字符串逐字符处理了,所以得到的是字符拆分结果。下面是两种正确的实现方式:
方法一:使用Python标准库(无额外依赖)
import json import csv # 读取并解析config.json,获取CSV文件路径 with open('config.json', 'r', encoding='utf-8') as config_file: config_data = json.load(config_file) csv_file_path = config_data['mortalityfile'] # 读取CSV文件内容 csv_content = [] with open(csv_file_path, 'r', encoding='utf-8') as file: # 创建CSV读取器 csv_reader = csv.reader(file) # 读取表头(如果CSV没有表头可删除此行) header = next(csv_reader) csv_content.append(header) # 读取所有数据行 for row in csv_reader: csv_content.append(row) # 打印结果 for line in csv_content: print(line)
方法二:使用Pandas(更简洁,适合数据处理)
如果已安装Pandas库,这种方式更高效:
import json import pandas as pd # 解析config.json获取路径 with open('config.json', 'r', encoding='utf-8') as f: config = json.load(f) csv_path = config['mortalityfile'] # 读取CSV并输出 df = pd.read_csv(csv_path) print(df) # 如需转成列表格式 csv_list = df.values.tolist() print(csv_list)
关键说明
json.load()会把JSON文件内容解析为Python字典,直接通过键名mortalityfile就能提取路径,这是核心步骤。- 使用
with语句操作文件可自动关闭文件,避免资源浪费。 - 标准库方法适合无额外依赖的场景,Pandas则更适合后续的数据清洗、分析等操作。
内容的提问来源于stack exchange,提问作者Chinnari
相关产品推荐
相关产品推荐

