加载图像时如何避免权限错误

我有一个图像文件夹:


images

  |- some images.png

  |- grasses

     |- grass images.png

当我想打开图像时,例如:


for image_file_name in os.listdir("images/grasses"):

  image_file_id = image_file_name.split(".")[0]

  with open("images/grasses/" + image_file_name) as file:

    surface = pygame.image.load(file)

    surfaces[image_file_id] = surface

我明白了:


 Traceback (most recent call last):

   File "C:/Users/USER/PycharmProjects/Rock Rain/Rock Rain.py", line 43, in <module>

     with open("images/" + image_file_name) as file:

 PermissionError: [Errno 13] Permission denied: 'images/grasses'

我检查了这个文件夹的权限,但这不是问题。问题是什么 ?


吃鸡游戏
浏览 88回答 1
1回答

开心每一天1111

问题是您没有过滤要打开的数据。os.listdir列出目录中的所有内容,包括其他子目录。在您的情况下,您列出了包含子目录“grasses”的“images”,而您不能创建open目录。至少检查文件类型和扩展名for image_file_name in os.listdir("images/grasses"):&nbsp; image_file_id = image_file_name.split(".")[0]&nbsp; fullname = os.path.join("images/grasses", image_file_name)&nbsp; if fullname.endswith(".png") and os.path.isfile(fullname):&nbsp; &nbsp; with open(fullname, "rb") as file:&nbsp; &nbsp; &nbsp; surface = pygame.image.load(file)&nbsp; &nbsp; &nbsp; surfaces[image_file_id] = surface
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python