将多个文件从dir随机移动到di

2024-05-15 01:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个脚本,将一个文件从一个目录复制到另一个目录。 有没有办法选择多个?例如,特别是源目录中文件总数的25%?我没有找到直接的答案。你知道吗

这就是我所拥有的。你知道吗

files = os.listdir(source_dir)
index = random.randrange(0, len(files))
random_file = files[index]
shutil.copy(source_dir + random_file, output_dir)

谢谢。你知道吗


Tags: 文件答案目录脚本sourceindexosdir
1条回答
网友
1楼 · 发布于 2024-05-15 01:54:42

试试这个。您可以将rootdir、output\u dir和percentage更改为您想要的任何值。你知道吗

import os, shutil
from random import choice

rootdir = 'C:/images'
output_dir = 'C:/copies'
for subdir, dir, files in os.walk(rootdir):
    if files:
        for x in range(int(len(files) *.25)):
            to_copy = choice(files)
            shutil.copy(os.path.join(subdir, to_copy), os.path.join(output_dir, to_copy))
            files.remove(to_copy)

相关问题 更多 >

    热门问题