如何将Python字典格式的TXT文件转换为CSV数据文件?
问题描述
我有一个包含300,000条记录的TXT文件,单条记录格式示例如下:
{'AIG': 'American International Group', 'AA': 'Alcoa Corporation', 'EA': 'Electronic Arts Inc.'}
我需要将这些记录导出为两列结构的CSV文件(第一列是股票代码,第二列是公司全称),但使用以下代码生成的CSV未在记录间换行,导致30万条记录在Excel中仅占两行,超出Excel列数上限无法完整显示:
import pandas as pd read_file = pd.read_csv (r'C:\...\input.txt') read_file.to_csv (r'C:\...\output.csv', index=None)
解决方案
原代码的问题在于pd.read_csv会把整行字典内容当作单个字段处理,没有解析内部的键值对。以下是两种可行的解决方法:
方法一:使用Python内置csv模块
import csv import ast input_path = r'C:\...\input.txt' output_path = r'C:\...\output.csv' with open(input_path, 'r', encoding='utf-8') as txt_file, open(output_path, 'w', newline='', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) # 写入表头 writer.writerow(['股票代码', '公司全称']) for line in txt_file: line = line.strip() if not line: continue try: # 安全解析字符串为字典 record_dict = ast.literal_eval(line) # 遍历键值对写入CSV行 for ticker, company in record_dict.items(): writer.writerow([ticker, company]) except Exception as e: print(f"解析行出错:{line},错误信息:{e}")
方法二:使用Pandas处理
如果偏好使用Pandas,需先解析每行的字典并展开为结构化数据:
import pandas as pd import ast input_path = r'C:\...\input.txt' output_path = r'C:\...\output.csv' records = [] with open(input_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if line: record_dict = ast.literal_eval(line) # 将字典转为列表字典,适配Pandas结构 records.extend([{'股票代码': k, '公司全称': v} for k, v in record_dict.items()]) # 生成DataFrame并写入CSV df = pd.DataFrame(records) df.to_csv(output_path, index=False, encoding='utf-8')
关键说明
ast.literal_eval比原生eval更安全,专门用于解析Python字面量(如字典、列表),避免执行恶意代码。- 逐行处理的方式可以避免一次性加载30万条数据到内存,降低内存占用压力。
- 最终生成的CSV为每行对应一条股票代码+公司全称的格式,完全适配Excel的显示逻辑。
内容的提问来源于stack exchange,提问作者HTMLHelpMe
相关产品推荐
相关产品推荐

