Python实现带列结构文本文件转JSON的问题求助
问题分析与修复方案
核心问题
- 文件格式处理错误:你要处理的不是CSV文件,而是每行以
文件路径:属性名: 属性值格式存储的文本文件,但误用了CSV读取器(csv.DictReader)处理,导致程序把第一行整串当成表头,后续每行整串当成对应值,生成了完全混乱的键值对。 - JSON写入重复:
convert_write_json函数里连续调用两次json.dumps(data)并写入文件,导致输出的JSON内容重复了两遍。
修正后的代码
import json from pathlib import Path def read_font_info(file_path, json_file): font_data = {} with open(file_path, 'r') as f: for line in f: line = line.strip() if not line: continue # 分割路径、属性名、属性值:先切第一个冒号,再切剩余部分的第一个冒号 path_part, rest = line.split(':', 1) attr_name, attr_value = rest.split(':', 1) # 去除属性名和值的多余空格 attr_name = attr_name.strip() attr_value = attr_value.strip() # 合并同一文件的所有属性 if path_part not in font_data: font_data[path_part] = {} font_data[path_part][attr_name] = attr_value # 转换为易读的列表结构(支持多文件) result = [{"file_path": path, "attributes": attrs} for path, attrs in font_data.items()] # 写入格式化后的JSON with open(json_file, 'w') as f: json.dump(result, f, indent=4) # 遍历文件夹目标文件(根据实际后缀修改,比如.txt或你用的.csv) folder_path = "/users/user/CSVtoGD/" files = Path(folder_path).glob('*.csv') # 是txt文件就改成*.txt for f in files: read_font_info(f, str(f.with_suffix('.json')))
代码说明
- 读取逻辑:逐行解析内容,精准分割出文件路径、属性名和属性值,把同一文件的所有属性整理到一个字典中,最终生成包含文件路径和属性集合的清晰结构。
- 写入逻辑:仅调用一次
json.dump,生成格式化、无重复的标准JSON内容。 - 多文件适配:文件夹内所有目标格式文件会被分别处理,各自生成对应的JSON文件。
预期输出示例
[ { "file_path": "Assets/HighroadEngine/MMTools/Achievements/Fonts/orange kid.ttf", "attributes": { "Family": "Orange Kid", "Subfamily": "Regular", "Full name": "OrangeKid-Regular", "PostScript name": "OrangeKid-Regular", "Preferred family": "Orange Kid", "Preferred subfamily": "Regular", "Mac font menu name": "OrangeKid-Regular", "Version": "OTF 4.000;PS 001.001;Core 1.0.29", "Unique ID": "4.000;LARA;OrangeKid-Regular" } } ]
内容的提问来源于stack exchange,提问作者Kamilminiprogramer
相关产品推荐
相关产品推荐

