2017-06-05 23 views
0

我需要遍歷文件夾名稱,然後通過圖像,但我有這個錯誤。可能有人告訴我如何避免錯誤?如何避免將字符串添加到生成器表達式的錯誤?

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) 

回答

1

該錯誤是從以前的行,其中你想添加path到發電機EXP未來:

path+(x for x in dirs) 

你應該加入path到目錄名稱中使用os.path.join

for dir in dirs: 
    for img in os.listdir(os.path.join(path, dir)): 
     ... 
1
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) 
1

您不必要地通過使用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) 

應該就夠了。

+0

謝謝,這正是我想要的 –

相關問題