【问题标题】:Placing randomly selected images into new folder将随机选择的图像放入新文件夹
【发布时间】:2019-11-27 10:42:22
【问题描述】:

我有一个包含大量子目录的目录。

在每个子目录中都有不同的 jpeg、png。

我想:

从这些子目录中选择 X 个随机图像

创建一个新文件夹并将这些选定的随机图像复制到其中。

感谢这里已经收到的帮助,我可以使用os.walkrandom.choice 打印出随机选择的图像。

import os
import random
import shutil


files_list = []
for root, dirs, files in os.walk("/Path/to/Directory"):
    for file in files:
        #all 
        if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
            files_list.append(os.path.join(root, file))


#print images
#lets me count and print the amount of jpeg,jpg,pmg 
file_count = len(files_list)
print file_count

print files_list   
print(random.sample(files_list, 2))  #prints two random files from list 

但是,我的问题是实际选择随机图像(不是它们的名称)

我试图创建一个使用 os.walk 的变量 imagePath

#creates a variable imagePath that lets me access all img files in different folders
imagePath = os.walk("/Path/to/Directory") 

和一个新变量,用于从 imagePath 中随机选择单个图像

#create a variable that lets me choose random iamge from imagePath
randomImages = random.choice(os.listdir(imagePath)) 

然后创建一个新目录并使用shutil.copy 将 radnomally 选择的图像移动到这个新目录中

#creates a new directory 
os.mkdir('testDirectory')

#moves the randomly selected image into new directory 
shutil.copy(randomImages, testDirectory)

但是,我收到以下错误:

Traceback (most recent call last):
  File "crawl.py", line 28, in <module>
    randomImages = random.choice(os.listdir(imagePath)) 
TypeError: coercing to Unicode: need string or buffer, generator found

我也试过


for root, dirs, files in os.walk("/Path/to/Directory", topdown=False):
    imagePath = ("/Path/to/Directory") #creates a variable that lets me access all img files in different folders
    randomImages = random.choice(os.listdir(imagePath)) 
    print randomImages

但这会返回随机选择的子目录(不是其中的图像)以及 .ds 存储文件。

【问题讨论】:

  • 我认为问题出在 imagePath,os.listdir(imagePath)os.listdir 将目录的字符串路径作为参数,imagePath 不是,尝试集成这行代码,迭代结果并获取目录。 for root, dirs, files in os.walk(".", topdown=False):os.walk() 文档,[tutorialspoint.com/python/os_walk.htm]
  • 感谢@n0thing 我已经尝试过这个并用新问题更新了我的 OP。

标签: python image random shutil os.walk


【解决方案1】:

这是代码,我猜你想移动文件而不是制作另一个副本。

import os
import random
import shutil


files_list = []

for root, dirs, files in os.walk("<SOURCE_DIR>"):
    for file in files:
        #all 
        if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
            files_list.append(os.path.join(root, file))


#print images
#lets me count and print the amount of jpeg,jpg,pmg 
file_count = len(files_list)
print file_count

# print files_list   
filesToCopy = random.sample(files_list, 2)  #prints two random files from list 

destPath = "<DESTINATION_DIR>"

# if destination dir does not exists, create it
if os.path.isdir(destPath) == False:
        os.makedirs(destPath)

# iteraate over all random files and move them
for file in filesToCopy:
    shutil.move(file, destPath)

【讨论】:

    【解决方案2】:

    您应该能够为 shutil.copy() 提供源和目标文件路径。在我看来,您已经有一个文件列表,因此您可以复制它们。

    import os
    import random
    import shutil
    
    
    files_list = []
    for root, dirs, files in os.walk("/Path/to/Directory"):
        for file in files:
            #all 
            if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg"):
                files_list.append(os.path.join(root, file))
    
    
    #print images
    #lets me count and print the amount of jpeg,jpg,pmg 
    file_count = len(files_list)
    print file_count
    
    print files_list   
    selected_files = random.sample(files_list, 2))  #assign to a list
    
    dest_path = "/path/to/new/folder/"
    os.mkdir(dest_path)
    
    for src_path in selected_files:
        shutil.copy(src_path, os.path.join(dest_path, os.path.basename(src_path)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 2014-07-29
      • 2012-06-10
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 2014-01-28
      相关资源
      最近更新 更多