目录下大约有2000个文档。我想随机选择一些文档并自动将它们复制到新目录。
关于在某个目录下生成一个文档名的一些相关信息。
尝试:
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)
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)
destPath = os.path.join(destDirectory, fname)
shutil.copyfile(srcpath, destPath)
根据@inspectorG4dget 的回答(并由@olinox14 编辑),我发现这个小调整最适合我的情况。我不断从 shutil.copyfile() 得到一个“IsDirectoryError”,所以我检查了文档并意识到函数复制到文件(而不是目录)。此调整将文件名保留在新目录中。