diff --git a/csv2json b/csv2json new file mode 100755 index 0000000..7227996 --- /dev/null +++ b/csv2json @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import csv +import json +import sys +import os + +def main(): + if len(sys.argv) < 2: + print("❌ 使用错误!") + print("用法: csv2json <输入CSV文件路径> [输出JSON文件路径]") + sys.exit(1) + + csv_path = sys.argv[1] + json_path = sys.argv[2] if len(sys.argv) == 3 else os.path.splitext(csv_path)[0] + ".json" + + try: + cleaned_data = [] + + with open(csv_path, mode='r', encoding='utf-8-sig') as f: + reader = csv.DictReader(f) + + for row in reader: + # 💡 核心过滤逻辑: + # 只有当 key 不为 None、不为空字符串、且去掉空格后不为空时,才保留该列 + filtered_row = { + key: value + for key, value in row.items() + if key is not None and str(key).strip() != "" + } + + # 只有这一行过滤后还包含有效数据,才写入结果 + if filtered_row: + cleaned_data = cleaned_data + [filtered_row] + + with open(json_path, mode='w', encoding='utf-8') as f: + json.dump(cleaned_data, f, indent=4, ensure_ascii=False) + + print(f"✅ 成功排除空列并转换: {csv_path} -> {json_path}") + except Exception as e: + print(f"❌ 转换失败: {e}") + +if __name__ == '__main__': + main()