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

如何使用pathlib将批量生成的文件对应存入各文件夹?

实现随机文件生成并自动移动到对应文件夹

需求说明

现有代码可根据输入的迭代次数生成randomfile1.txt这类带随机内容的文件,同时创建Sample1、Sample2等文件夹,需要把每个randomfilei.txt自动移到对应的Samplei文件夹中。

修改后的完整代码

import shutil
import random
import getpass
from pathlib import Path

def sample() -> None:
    username = getpass.getuser()
    # 统一管理根目录,用Path简化路径操作
    root_dir = Path(f"C:/Users/{username}/PycharmProjects/SampleProject")
    number_of_iteration = int(input("Enter the number of iterations needed\n"))

    for i in range(1, number_of_iteration + 1):
        file_name = f"randomfile{i}.txt"
        source_file = root_dir / file_name
        target_dir = root_dir / f"Sample{i}"
        
        # 写入随机内容到文件
        with open(source_file, 'w') as f:
            list_of_something = [something1, something2, something3]
            selected_dict = random.choice(list_of_something)
            for key, value in selected_dict.items():
                # 替换成你实际的写入逻辑,示例写入键值对
                f.write(f"{key}: {value}\n")
        # 追加内容(保留原代码的追加逻辑)
        with open(source_file, 'a') as f:
            # 替换成你实际的追加内容
            f.write("这是追加的内容\n")
        
        # 创建目标文件夹,已存在则跳过
        target_dir.mkdir(parents=True, exist_ok=True)
        # 移动文件到对应Sample文件夹
        shutil.move(str(source_file), str(target_dir / file_name))

# 定义随机选择的字典
something1 = {'a' : 'b'}
something2 = {'c' : 'd'}
something3 = {'x' : 'y'}

# 执行主函数
if __name__ == "__main__":
    sample()

核心修改说明

  1. 路径优化:用Path类统一处理路径,避免重复拼接字符串,减少出错概率
  2. 文件移动:在创建完Samplei文件夹后,调用shutil.move()将生成的文件直接移到目标文件夹,完成需求
  3. 代码健壮性:添加了脚本入口if __name__ == "__main__",方便直接运行
  4. 示例填充:补充了基础的写入逻辑,替换原代码中的注释占位,方便直接测试运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:38:21