【问题标题】:How can I open a series of files (PNGs) from a specified directory (randomly) using Python?如何使用 Python 从指定目录(随机)打开一系列文件(PNG)?
【发布时间】:2015-10-03 18:33:27
【问题描述】:

我在指定目录中有一个文件夹,其中包含几个需要随机打开的 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。到目前为止我失败了。有什么想法吗?

【问题讨论】:

  • 打开它们是什么意思?
  • 如何将os.path.join(root, file)的结果添加到数组中,然后随机访问数组的条目?
  • 我希望程序打开图像进行查看。不过,它们需要按随机顺序排列。我知道将它们全部同时打开时将它们随机化并没有什么意义,但我会将此代码集成到另一个程序中,一次只能打开一个图像。
  • 然后用油漆打开它们?还是?
  • 最终,图像将需要显示在外部屏幕上(可能在 Tkinter 窗口中)。

标签: python random shuffle


【解决方案1】:

我在指定目录中有一个文件夹,其中包含多个 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:
        ...

【讨论】:

  • 我喜欢第一种方法,但是之后如何打开文件呢?我不能使用files.open
  • @Mickey,我会编辑,这只是一个循环的问题,你到底想对文件做什么?
  • 最终,它们将需要在一个单独的 Tkinter 窗口中按照我们使用 shuffle 指定的随机顺序一次打开一个。
  • 嗯,好的,然后迭代就可以了
  • 我遇到了同样的问题 - 我无法打开实际图像。使用open(fle) as f:,输出是经过洗牌的路径列表,而不是图像本身。当我尝试file.open 时,我收到一条错误消息:“type object 'file' has no attribute 'open'。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2021-12-07
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2013-03-18
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多