随机拷贝指定文件夹内的文件到其他文件夹。
import os
import random
import shutil
def newDir(fileDir):
fileDir = fileDir.strip()
if not os.path.exists(fileDir):
os.makedirs(fileDir)
else:
print(fileDir+'already exists!!!')
def randomCopyFile(sourDir, dstDir, num):
pathDir = os.listdir(sourDir)
newDir(dstDir)
samples = random.sample(pathDir, num)
for sample in samples:
print(sample)
if os.path.isfile(os.path.join(sourDir, sample)):
shutil.copy(sourDir+sample, dstDir+sample)
if __name__ == '__main__':
source = "/home/w/data/folder/"
dst = "/home/x/data/folder/"
num = 500
randomCopyFile(source, dst, num)