如何避免将字符串添加到发电机表达式中的错误



我需要迭代文件夹名称,然后遍历图像,但是我有一个错误。有人可以告诉我如何避免错误吗?

path = '/.../'
dirs = next(os.walk(path))[1] # get my folder names inside my directory
for i in dirs:
    for img in os.listdir(path+(x for x in dirs)): <------ TypeError: must be str, not generator
        img_path = os.path.join(path,img)  
        print(img_path)

错误来自上一行,您要尝试将 path添加到发电机exp:

path+(x for x in dirs)

您应该使用os.path.join加入path到目录名称:

for dir in dirs:   
   for img in os.listdir(os.path.join(path, dir)):
      ...

您不必使用listdir使代码复杂化。这个:

import os, os.path
path = '/.../'
for d, _, files in os.walk(path):
    for f in files:
        img_path = os.path.join(d, f)
        print(img_path)

应该足够。

import os
path = '/home/'

dirs = next(os.walk(path))[1]  # get folder names inside directory
for i in dirs:
    for img in os.listdir(path+i):
        img_path = os.path.join(path,img)  
        print(img_path)

在下面的行中,您正在尝试将生成器对象和字符串path加在一起。相反,您可以使用i本身,如上所述。

path+(x for x in dirs)

最新更新