代码之家  ›  专栏  ›  技术社区  ›  physlexic

在目录之间随机移动多个文件

  •  0
  • physlexic  · 技术社区  · 7 年前

    我编写了一个脚本,将单个文件从一个目录复制到另一个目录。 有没有办法选择多个?一、 e.特别是源目录中文件总数的25%?我还没有找到一个直接的答案。

    这就是我所拥有的。

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

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Chris    7 年前

    试试这个。您可以根据需要更改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)