场景: 现在一个文件夹目录下面有很多子文件夹,每个子文件夹下面都有若干图片,需要从每个子文件夹下面随机选取一张图片,存入新的文件夹。
代码很简单,但是很使用,你还可以根据自己的需要改成各种功能,比如把一张图片换成若干图片等。
def random_copyfile(srcPath,dstPath):
for dir_info in os.walk(srcPath):
dir_name, _, file_names = dir_info
temp = []
for file_name in file_names:
temp.append(file_name)
if len(temp) == 0:
continue
randomfile = random.choice(temp)
I = Image.open(os.path.join(dir_name,randomfile))
I.save(os.path.join(dstPath,temp[0]))
if __main__ == '__main__':
srcPath='.//img'
dstPath = './/all_img'
random_copyfile(srcPath,dstPath)