艺赛旗 RPA8.0全新首发免费下载 点击下载
http://www.i-search.com.cn/index.html?from=line1 详细内容请参看艺赛旗官网支持栏目:RPA社区
点击链接进入 http://support.i-search.com.cn/
怎么遍历输出某路径下的所有问价和文件夹?
这个问题和,“指定一个节点,输出以这个节点作为根节点的这棵树的所有子节点”一样。
递归可以实现。
如果是叶子节点(文件)了,就输出这个叶子节点的名称,返回。
否则,输出这个节点的名称(文件夹),并以这个结点再次作为根节点,遍历输出它的所有子节点。
-- coding: utf-8 --
import os
def traverse(f):
fs = os.listdir(f)
for f1 in fs:
tmp_path = os.path.join(f,f1)
if not os.path.isdir(tmp_path):
print(‘文件: %s’%tmp_path)
else:
print(‘文件夹:%s’%tmp_path)
traverse(tmp_path)
path = ‘F:/source_files/python/’
traverse(path)
有个问题需要注意的是,用 os.listdir() 这个函数,只会返回路径下的所有文件名(而这些文件名不含路径)……
所以要写成绝对路径。可以用 os.path.join 这个函数。
In [1]: import os
In [2]: os.path.join(‘a’,‘b