繁体   English   中英

如何使用Python从指定目录(随机)打开一系列文件(PNG)?

[英]How can I open a series of files (PNGs) from a specified directory (randomly) using Python?

我在指定目录中有一个文件夹,其中包含几个需要随机打开的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))

这将返回文件夹中的图像列表。 我想也许我可以以某种方式将print的输出随机化然后使用open 我到目前为止失败了。 有任何想法吗?

您可以先创建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

我在指定目录中有一个包含几个PNG的文件夹 您不需要也不应该使用os.path.walk搜索特定目录,它也可能会添加来自其他子目录的文件,这会导致错误的结果。 您可以使用glob获取所有png的列表然后随机播放:

from random import shuffle
from glob import glob
files = glob(r"C:\Users\Mickey\Desktop\VisualAngle\sample images\*.png")
shuffle(files)

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)

打开:

for fle in files:
   with open(fle) as f:
        ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM