问题
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