使用 random 和 shutil 在 python 中循环移动文件



我有一个小问题。我正在尝试在 20 个预定义文件夹中移动 500x20 图像。我可以用 500 张随机图像来完成这项工作,我已经确定了问题所在;我绘制了 500 个随机文件,移动它们,然后尝试再次执行此操作,但由于它不更新随机列表,因此当它到达它认为是随机组一部分但已被移动的图像时它会失败,因此失败。如何"更新"随机文件列表,使其不会因为我移动内容而失败?代码为:

import os
import shutil
import random
folders = os.listdir(r'place_where_20_folders_are')
files = os.listdir(r'place_where_images_are')
string=r"string_to_add_to_make_full_path_of_each_file"
folders=[string+s for s in folders]
for folder in folders:
for fileName in random.sample(files, min(len(files), 500)):
path = os.path.join(r'place_where_images_are', fileName)
shutil.move(path, folder)

我认为您的代码中的问题是random.sample()方法保持原始files列表不变。因此,您有机会两次获得相同的文件名,但由于您之前已经移动了它,因此会出现错误。

您可以使用以下代码片段,而不是使用sample

files_to_move = [files.pop(random.randrange(0, len(files))) for _ in range(500)]

这将从文件列表中弹出(从而删除(500个随机文件并将它们保存在files_to_move中。当您重复此操作时,files列表会变小。

这个答案的灵感来自对问题的回答 随机样本 从列表中删除。

这将像这样使用:

import os
import shutil
import random
folders = os.listdir(r'place_where_20_folders_are')
files = os.listdir(r'place_where_images_are')
string=r"string_to_add_to_make_full_path_of_each_file"
folders=[string+s for s in folders]
for folder in folders:
files_to_move = [files.pop(random.randrange(0, len(files))) for _ in range(500)]
for file_to_move in files_to_move:
path = os.path.join(r'place_where_images_are', file_to_move)
shutil.move(path, folder)

我会首先创建一个随机样本列表,然后传递它以在不同位置移动,并使用随机库删除我的列表remove(),或者只是在循环再次开始之前清除/删除/弹出列表本身。

希望它有帮助。

最新更新