我正在尝试编写一个处理各种子目录中的文件的处理程序,但是当我的脚本可以看到这些文件时,它无法对它们做任何事情,因为它无法组装它们的路径.
有问题的部分来自这个循环:
for (path, dirs, files) in os.walk("data/"):
for image in files:
#do something to the image
Run Code Online (Sandbox Code Playgroud)
现在,该脚本在data
目录的第一级工作,但无法处理data
子目录.
我试过用os.path.join()
:
for (path, dirs, files) in os.walk("data/"):
print os.path.join(path, dirs)
Run Code Online (Sandbox Code Playgroud)
但是这引发了以下情况:
Traceback (most recent call last):
File "bench.py", line 26, in <module>
print os.path.join(path, dirs)
File "/usr/lib/python2.7/posixpath.py", line 75, in join
if b.startswith('/'):
AttributeError: 'list' object has no attribute 'startswith'
Run Code Online (Sandbox Code Playgroud)
简而言之,我想要做的就是从data
包含data
子目录的图像中组装一条路径.这样做的最佳做法是什么?
我认为你要加入path
与file
每个file
在files
for path,dirs,files in os.walk('data/'):
for f in files:
fname = os.path.join(path,f)
assert(os.path.exists(fname))
Run Code Online (Sandbox Code Playgroud)
dirs
是list
目录中的目录path
.您可以实际修改dirs
以防止os.walk
进入某些目录(整洁!).