How to import all images from a user specified folder in python using pygame

对着背影说爱祢 提交于 2021-01-28 07:55:14

问题


I m new to python, and I'm working on pygame. For my project, i need to import all the images from a user specified folder. Is there any function in pygame to import only the image files from the folder? or guide me to filter only the image files among all files from the imported folder. Sorry, if the question is too basic.


回答1:


I don't know about pygame but you with plain python is fairly simple to get all image files within a folder:

import imghdr
import os

for dirpath, dirnames, filenames in os.walk('FOLDER'):
    for filename in filenames:
        file_path = os.path.join(dirpath, filename)
        if imghdr.what(file_path):
            print file_path, ' is an image'

This works by exploring 'FOLDER' recursively. We check if the file is an image by using the imghdr builtin module. You can even filter out image types you're not interested by checking what the imghdr.what() function returns.



来源:https://stackoverflow.com/questions/22420127/how-to-import-all-images-from-a-user-specified-folder-in-python-using-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!