【发布时间】:2019-11-27 10:42:22
【问题描述】:
我有一个包含大量子目录的目录。
在每个子目录中都有不同的 jpeg、png。
我想:
从这些子目录中选择 X 个随机图像
创建一个新文件夹并将这些选定的随机图像复制到其中。
感谢这里已经收到的帮助,我可以使用os.walk 和random.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