如何每次运行脚本时将Pandas DataFrame保存为不同名称的JSON文件
解决Pandas导出JSON时覆盖文件的问题
问题分析
你之前尝试用时间戳生成文件名失败,大概率是因为原代码的时间格式包含空格(%Y-%m-%d %X里的空格),部分系统不允许文件名带空格;另外可能未导入time模块导致报错。
可行解决方案
方案1:用无特殊字符的时间戳生成文件名
使用datetime模块生成不含空格和冒号的时间戳,确保文件名合法:
import pandas as pd from datetime import datetime # 生成格式为YYYYMMDD_HHMMSS的时间戳 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # 拼接文件名和路径 file_path = f"Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context/rand_search_{timestamp}.json" # 导出JSON df2.to_json(file_path)
方案2:时间戳+随机数,避免同一秒多次运行冲突
如果脚本可能在同一秒内多次执行,加上随机后缀彻底避免覆盖:
import pandas as pd from datetime import datetime import random timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # 生成3位随机数作为后缀 random_suffix = random.randint(100, 999) file_path = f"Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context/rand_search_{timestamp}_{random_suffix}.json" df2.to_json(file_path)
方案3:按递增编号生成文件名
如果偏好类似Office_15的编号格式,可以遍历目录下已有文件,自动生成下一个编号:
import pandas as pd import os dir_path = "Desktop/Thesis_Brainstorm/Thesis_Code/Office_Context" # 筛选所有Office_前缀的JSON文件 existing_files = [f for f in os.listdir(dir_path) if f.startswith("Office_") and f.endswith(".json")] if existing_files: # 提取已有编号并找出最大值 max_num = max(int(f.split("_")[-1].split(".")[0]) for f in existing_files) next_num = max_num + 1 else: next_num = 1 file_path = os.path.join(dir_path, f"Office_{next_num}.json") df2.to_json(file_path)
内容的提问来源于stack exchange,提问作者Nicolas Alexander Lomas
相关产品推荐
相关产品推荐

