csv2json.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import csv
  2. import json
  3. import os
  4. def csv_to_json(csv_file_path, json_file_path=None, encoding='utf-8'):
  5. """
  6. 将CSV文件转换为JSON文件
  7. 参数:
  8. csv_file_path: CSV文件路径
  9. json_file_path: JSON文件输出路径(可选,默认为CSV同目录同名.json)
  10. encoding: 文件编码格式
  11. """
  12. # 检查CSV文件是否存在
  13. if not os.path.exists(csv_file_path):
  14. print(f"错误:找不到CSV文件 '{csv_file_path}'")
  15. return False
  16. # 设置JSON输出路径
  17. if json_file_path is None:
  18. base_name = os.path.splitext(csv_file_path)[0]
  19. json_file_path = f"{base_name}.json"
  20. try:
  21. # 读取CSV文件
  22. with open(csv_file_path, 'r', encoding=encoding) as csv_file:
  23. # 使用csv.DictReader读取数据
  24. csv_reader = csv.DictReader(csv_file)
  25. # 将数据转换为列表
  26. data = list(csv_reader)
  27. # 数据类型转换(可选)
  28. for item in data:
  29. # 尝试将数值字段转换为浮点数
  30. for key in ['txAmount', 'txBalance']:
  31. if key in item and item[key]:
  32. try:
  33. item[key] = float(item[key])
  34. except ValueError:
  35. pass # 如果转换失败,保持原样
  36. # 创建完整的日期时间字段(可选)
  37. if 'txDate' in item and 'txTime' in item:
  38. item['txDateTime'] = f"{item['txDate']} {item['txTime']}"
  39. print(f"成功读取 {len(data)} 条记录")
  40. # 写入JSON文件
  41. with open(json_file_path, 'w', encoding='utf-8') as json_file:
  42. json.dump(data, json_file, ensure_ascii=False, indent=2)
  43. print(f"JSON文件已保存到: {json_file_path}")
  44. print(f"文件大小: {os.path.getsize(json_file_path)} 字节")
  45. # 显示前几条记录作为示例
  46. print("\n前3条记录示例:")
  47. for i, record in enumerate(data[:3]):
  48. print(f"\n记录 {i + 1}:")
  49. for key, value in record.items():
  50. print(f" {key}: {value}")
  51. return True
  52. except FileNotFoundError:
  53. print(f"错误:找不到文件 '{csv_file_path}'")
  54. return False
  55. except UnicodeDecodeError:
  56. print(f"错误:编码问题,请尝试使用不同的编码格式(如'gbk')")
  57. return False
  58. except Exception as e:
  59. print(f"错误:处理文件时发生错误 - {str(e)}")
  60. return False
  61. # 使用示例
  62. if __name__ == "__main__":
  63. # 请根据实际情况修改这些参数
  64. csv_file = "交易流水样例数据.csv" # 您的CSV文件名
  65. json_file = "test_temp_agriculture_transaction_flow.json" # 输出的JSON文件名
  66. file_encoding = "utf-8" # 文件编码
  67. print("开始转换CSV到JSON...")
  68. print(f"CSV文件: {csv_file}")
  69. print(f"JSON文件: {json_file}")
  70. print(f"编码格式: {file_encoding}")
  71. print("-" * 50)
  72. # 执行转换
  73. success = csv_to_json(csv_file, json_file, file_encoding)
  74. if success:
  75. print("\n✓ 转换完成!")
  76. else:
  77. print("\n✗ 转换失败,请检查错误信息")