使用 Image.open(fnames) 无法打开图像并且代码出现“'list' 对象没有属性 'read'”错误

Images don't open using Image.open(fnames) and code have " 'list' object has no attribute 'read' " error

我有一些子文件夹 (s1,s2,s3,...)。我想打开路径中 "Image" 文件夹的子文件夹中的图像:
"E:/Image/" 并向他们展示。但是图片打不开

import os
from PIL import Image
root = "E:/Image/" 
path = os.path.join(root,"")
for r in os.walk(path):
     for file in r:
        fnames = glob.glob(f'{root}{r}/{file}')
        img1 = Image.open(fnames)
        img1.show()  

我的代码有这个错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
   2546     try:
-> 2547         fp.seek(0)
   2548     except (AttributeError, io.UnsupportedOperation):

AttributeError: 'list' object has no attribute 'seek'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-5-e9dafc96965e> in <module>()
      9         fnames = glob.glob(f'{root}{r}/{file}')
     10 
---> 11         img1 = Image.open(fnames)
     12        
     13         img1.show()

~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
   2547         fp.seek(0)
   2548     except (AttributeError, io.UnsupportedOperation):
-> 2549         fp = io.BytesIO(fp.read())
   2550         exclusive_fp = True
   2551 

AttributeError: 'list' object has no attribute 'read'

您得到异常是因为您将列表而不是文件名传递给 Image.open

然而,我看到的主要问题与 os.walk and glob.glob 的错误使用有关。 我建议在使用您不知道的功能之前仔细阅读文档。

澄清:

  • os.walk 不是 return path 中的文件名,而是递归地,目录 (dirpath)、子目录列表 (dirnames) 和目录中的文件列表 (filenames)。您可以简单地为 filenames.
  • 中的每个 name 执行 os.path.join(dirpath, name) 来获取所有文件名
  • glob.glob returns 匹配给定通配符的文件列表。从您的代码中,我想您希望 f'{root}{r}/{file}' 是系统上文件的名称,因此没有必要使用 glob.glob
  • 让您的生活复杂化

几个注意事项:

  • 由于您的 root 已经有尾随 /,因此调用 os.path.join(root,"") 什么都不做;
  • 如果要以编程方式创建文件路径,请不要手动添加路径分隔符,而是尽量使用os.path.join(或必要时使用os.sep) (它有助于保持跨系统兼容性)。作为例子而不是做

    root = "E:/Image/" 
    r = 'folder'
    file = 'test.txt'
    fname = f'{root}{r}/{file}'
    

    使用

    root = "E:/Image" 
    r = 'folder'
    file = 'test.txt'
    fname = os.path.join(root, r, file)
    

密码

现在是 "correct" 代码。由于我不知道您的目录结构、用户案例等,代码现在可能会按您的意愿运行,但我希望您可以根据自己的需要进行调整。

import os
from PIL import Image

root = "E:/Image/" 
for dirpath, _, filenames in os.walk(path):
    # we don't care about ``dirnames``
    for name in filenames:
        fname = op.path.join(dirpath, name)
        img1 = Image.open(fname)
        img1.show()