Mic*_*key 3 python random shuffle
我在指定目录中有一个文件夹,其中包含几个需要随机打开的PNG .我似乎无法开始random.shuffle处理该文件夹.到目前为止,我已经能够print获得内容,但它们也需要随机化,因此当它们打开时,序列是唯一的.
这是我的代码:
import os, sys
from random import shuffle
for root, dirs, files in os.walk("C:\Users\Mickey\Desktop\VisualAngle\sample images"):
for file in files:
if file.endswith(".png"):
print (os.path.join(root, file))
Run Code Online (Sandbox Code Playgroud)
这将返回文件夹中的图像列表.我想也许我可以以某种方式随机输出print然后使用open.我到目前为止失败了.有任何想法吗?
我在包含几个 PNG 的指定目录中有一个文件夹。您不需要也不应该使用os.path.walk搜索特定目录,它还可能会添加来自其他子目录的文件,这会给您带来不正确的结果。您可以使用glob获取所有 png 的列表,然后进行 shuffle:
from random import shuffle
from glob import glob
files = glob(r"C:\Users\Mickey\Desktop\VisualAngle\sample images\*.png")
shuffle(files)
Run Code Online (Sandbox Code Playgroud)
glob 还将返回完整路径。
您还可以使用os.listdir搜索特定文件夹:
pth = r"C:\Users\Mickey\Desktop\VisualAngle\sample images"
files = [os.path.join(pth,fle) for fle in os.listdir(pth) if fle.endswith(".png")]
shuffle(files)
Run Code Online (Sandbox Code Playgroud)
打开:
for fle in files:
with open(fle) as f:
...
Run Code Online (Sandbox Code Playgroud)
您可以先创建png文件名列表然后随机播放:
import os
from random import shuffle
dirname = r'C:\Users\Mickey\Desktop\VisualAngle\sample images'
paths = [
os.path.join(root, filename)
for root, dirs, files in os.walk(dirname)
for filename in files
if filename.endswith('.png')
]
shuffle(paths)
print paths
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1539 次 |
| 最近记录: |