我在Python 3中定义了一个函数..。
>>> import os
>>> def find(path):
... if not os.path.isdir(path):
... return []
... out_list = []
... for f in os.listdir(path):
... if os.path.isdir(f):
... for g in find(f):
... out_list.append(g)
... else:
... out_list.append(f)
... return out_list
...
它似乎会爬下path
树,列出每个文件(至少对我来说),但是当我执行时.
>>> find('..')
['CDB', 'dv', 'DataIntegrityUtility', 'cdb', 'libvrs']
所有的结果都有包含文件的目录。难道不应该有更多吗?
发布于 2015-01-02 21:37:32
在python中存在os.walk
。
os.walk('path') =>递归遍历目录,它给元组以目录,
子目录和文件
for x,y,z in os.walk('path'):
# z is the directory
# y is subdirectories
# x is the files
发布于 2015-01-02 21:45:52
问题是,
for f in os.listdir(path):
将使用路径中包含的“叶”名称进行迭代,例如,如果'/tmp/fooand it contains
barand
baz, then
fwill be
bar, then
baz`.是path
然后检查os.path.isdir('bar')
--这意味着当前目录中的'bar'
(如果有的话),而不是'/tmp'
下的那个!
所以你需要添加这样的东西
f = os.path.join(path, f)
在for
语句下面,其余的逻辑才能正确操作。(如果出于某种原因,只想在out_list
中使用叶名,就可以使用os.path.basename
从完整的路径字符串中提取它们)。
https://stackoverflow.com/questions/27748848
复制相似问题