【问题标题】:Automatically creating a list in Python [duplicate]在Python中自动创建列表[重复]
【发布时间】:2015-04-25 02:18:12
【问题描述】:

我的代码:

red_images =  'DDtest/210red.png'
green_images = 'DDtest/183green.png'

b = [red_images, green_images]
shuffle(b)

我有几百张图片,为了使我的代码尽可能简洁(并扩展我的 Python 知识),我想知道如何编写代码来自动获取文件夹中的文件并使其成为列表。

我在R中做过类似的事情,但我不确定如何在python中做到这一点。

【问题讨论】:

标签: python list


【解决方案1】:

你也可以使用os:

import os
from random import shuffle

# Base directory from which you want to search    
base_dir = "/path/to/whatever"

# Only take the files in the above directory
files = [f for f in os.listdir(base_dir) 
         if os.path.isfile(os.path.join(base_dir, f))]

# shuffle (in place)
shuffle(files)

【讨论】:

  • 效果很好,谢谢。 :)
【解决方案2】:
import glob
my_new_list = glob.glob("/your/folder/*")

【讨论】:

  • 如此简洁,我喜欢它。谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多