如何从包含图像的文件夹中获取随机生成的路径
How to get a randomly generated path from a folder with images
所以,我有一个文件夹,里面有一堆图片。有没有办法让我随机 select 其中之一和 return 图片的路径?
您可以使用 glob.glob
和 random.choice
:
import glob
import random
file_path = random.choice(glob.glob("/path/to/folder/*"))
import os
import random
folder_directory = r"C:/Users/Andrew/Desktop/Beta-Testing/memes"
file_path = folder_directory[:-1] + "\" + random.choice(os.listdir(folder_directory))
print('r"'+file_path+'"')
搞定这个
r"C:/Users/Andrew/Desktop/Beta-Testing/memes\meme10.jpeg"
对于这个问题,您需要子进程库(它在 shell 上运行命令并可以记录它们的输出),并且您需要随机库。对于初学者,您将需要目录的输出,因此类似这样的内容将为您提供字符串格式的输出:
from subprocess import Popen, PIPE
pipe = Popen("put the command here i.e. the path plus the command", stdout=PIPE, shell = True)
text = pipe.communicate()[0]
print(text)
使用变量文本你可以解析它(这个你必须自己弄清楚)并将所有文件放入一个列表中,从那里:
import random
chosen_file = random.choice(list_of_files)
list_of_files.remove(chosen_file) #this is so that you dont have the same photo twice
然后,bada-bing,bada-boom 你应该可以在目录中随机 select 照片,作为旁注确保你在子进程中包含照片的目录命令,除非您想将此 python 文件与它们
保存在同一文件夹中
希望对你有所帮助,祝一切顺利
import os
import random
# get a list of all the files in the folder
file_list = os.listdir(r"C:\Users\User\Desktop\images")
# get a random file from the list
random_file = random.choice(file_list)
# print the path of the random file
print(os.path.join(r"C:\Users\User\Desktop\images", random_file))
所以,我有一个文件夹,里面有一堆图片。有没有办法让我随机 select 其中之一和 return 图片的路径?
您可以使用 glob.glob
和 random.choice
:
import glob
import random
file_path = random.choice(glob.glob("/path/to/folder/*"))
import os
import random
folder_directory = r"C:/Users/Andrew/Desktop/Beta-Testing/memes"
file_path = folder_directory[:-1] + "\" + random.choice(os.listdir(folder_directory))
print('r"'+file_path+'"')
搞定这个
r"C:/Users/Andrew/Desktop/Beta-Testing/memes\meme10.jpeg"
对于这个问题,您需要子进程库(它在 shell 上运行命令并可以记录它们的输出),并且您需要随机库。对于初学者,您将需要目录的输出,因此类似这样的内容将为您提供字符串格式的输出:
from subprocess import Popen, PIPE
pipe = Popen("put the command here i.e. the path plus the command", stdout=PIPE, shell = True)
text = pipe.communicate()[0]
print(text)
使用变量文本你可以解析它(这个你必须自己弄清楚)并将所有文件放入一个列表中,从那里:
import random
chosen_file = random.choice(list_of_files)
list_of_files.remove(chosen_file) #this is so that you dont have the same photo twice
然后,bada-bing,bada-boom 你应该可以在目录中随机 select 照片,作为旁注确保你在子进程中包含照片的目录命令,除非您想将此 python 文件与它们
保存在同一文件夹中希望对你有所帮助,祝一切顺利
import os
import random
# get a list of all the files in the folder
file_list = os.listdir(r"C:\Users\User\Desktop\images")
# get a random file from the list
random_file = random.choice(file_list)
# print the path of the random file
print(os.path.join(r"C:\Users\User\Desktop\images", random_file))