随机选择一个目录下的100个文件

juj*_*uju 3 python python-3.x

目录下有大约2000个文件.我想随机选择一些文档并自动将它们复制到一个新目录.

有关在特定目录下生成一个文档名称的一些相关信息.

ins*_*get 8

尝试:

import shutil, random, os
dirpath = 'your/read/location'
destDirectory = 'your/destination'

filenames = random.sample(os.listdir(dirpath), 100)
for fname in filenames:
    srcpath = os.path.join(dirpath, fname)
    shutil.copyfile(srcpath, destDirectory)
Run Code Online (Sandbox Code Playgroud)

  • 如果您收到“Errno 13:权限被拒绝”,请尝试使用shutil.copy()而不是shutil.copyfile()。 (2认同)