You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux/Python如何依据record.txt列表创建缺失空JSON文件且不覆盖已有文件

Shell 实现方案

直接执行以下脚本即可,仅会创建缺失的空白JSON文件,不会修改已存在的temporary.json数据:

# 替换为你存放已有temporary.json的目标文件夹路径
TARGET_DIR="./target_dir"

while read -r file_path; do
    # 提取txt文件的纯文件名(去掉路径和.txt后缀)
    base_name=$(basename "$file_path" .txt)
    target_json="${TARGET_DIR}/${base_name}.json"
    # 仅当文件不存在时创建空白文件
    [ ! -f "$target_json" ] && touch "$target_json"
done < record.txt

如果目标文件夹就是当前执行脚本的目录,把TARGET_DIR的值改为.即可。

Python 实现方案

import os

# 按需修改以下两个路径
record_txt_path = "record.txt"
target_json_dir = "./target_dir"

# 自动创建目标文件夹(如果不存在)
os.makedirs(target_json_dir, exist_ok=True)

with open(record_txt_path, "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        # 提取纯文件名
        base_name = os.path.splitext(os.path.basename(line))[0]
        target_file = os.path.join(target_json_dir, f"{base_name}.json")
        # 不存在则创建空白文件
        if not os.path.isfile(target_file):
            with open(target_file, "w") as _:
                pass

内容的提问来源于stack exchange,提问作者ML85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:45:01