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

如何使用Python的pathlib在每个文件夹内创建独立文件?

将生成的随机文件移动到对应目录

要实现将每个生成的randomfile{i}.txt文件移动到对应的Sample{i}文件夹中,你可以使用shutil.move()函数,并结合pathlib简化路径管理。以下是修改后的完整代码:

import shutil
import random
import getpass
from pathlib import Path

def sample() -> None:
    username = getpass.getuser()
    # 定义项目根目录,避免重复硬编码路径
    project_root = Path(f"C:/Users/{username}/PycharmProjects/SampleProject")
    
    number_of_iteration = int(input("Enter the number of iterations needed: "))
    for i in range(1, number_of_iteration + 1):
        file_name = f"randomfile{i}.txt"
        file_path = project_root / file_name
        
        # 写入文件内容
        with open(file_path, 'w') as f:
            list_of_something = [something1, something2, something3]
            random_generator_of_something = random.choice(list_of_something)
            for key, value in random_generator_of_something.items():
                # 执行自定义操作
                f.write(f"{key}: {value}\n")  # 示例写入逻辑,可替换为你的实际代码
        # 追加内容(按需保留)
        with open(file_path, 'a') as f:
            f.write("Additional content\n")  # 示例追加逻辑
        
        # 创建目标文件夹
        sample_dir = project_root / f"Sample{i}"
        sample_dir.mkdir(parents=True, exist_ok=True)
        
        # 将文件移动到目标文件夹
        target_file_path = sample_dir / file_name
        shutil.move(str(file_path), str(target_file_path))

something1 = {'a': 'b'}
something2 = {'c': 'd'}
something3 = {'x': 'y'}

# 执行函数
sample()

核心修改说明:

  • 用Path对象统一管理路径,避免重复拼接字符串,提升代码可读性。
  • 在创建Sample{i}文件夹后,调用shutil.move()完成文件移动操作。
  • 补充了基础的写入/追加示例逻辑,你可以替换为原代码中的自定义操作。

内容的提问来源于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 10:00:24