【问题标题】:Using random and shutil to move files in loop in python在python中使用random和shutil循环移动文件
【发布时间】:2019-12-14 17:38:06
【问题描述】:

我有一个小问题。我正在尝试在 20 个预定义文件夹中移动 20x500 图像。我只需使用 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)

【问题讨论】:

    标签: python random shutil


    【解决方案1】:

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

    你可以使用这个 sn-p,而不是使用 sample

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

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

    这个答案的灵感来自this answer 对问题Random Sample with remove from List

    这样使用:

    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)
    

    【讨论】:

    • 好的,我知道它是如何工作的,但它去哪儿了?我似乎无法放置它。
    • 我添加了一个似乎缺少的括号,但我收到此错误:文件“C:/Users/.../move_test.py”,第 25 行,在 files_to_move = [files .pop(random.randrange(0, len(files)) for _ in range(500))] TypeError: 'generator' 对象不能被解释为整数
    • 缺少括号,但位置错误。对于那个很抱歉。使用更新后的代码重试。
    【解决方案2】:

    我会首先制作一个随机样本列表,然后将其传递到不同的位置,并通过使用随机库 remove() 删除我的列表,或者只是在循环开始之前清除/删除/弹出列表本身再次。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      相关资源
      最近更新 更多