获取目录的树结构

时间:2013-06-05 01:15:11

标签: python file

我试图使用this StackOverflow answer中给出的代码。但是,我不明白该行是什么

level = root.replace(startpath, '').count(os.sep)

应该这样做。

此外,当我运行代码时,它在行

上给出了错误ValueError: zero length field name in format
print('{}{}/'.format(indent, os.path.basename(root)))

2 个答案:

答案 0 :(得分:2)

level = root.replace(startpath, '').count(os.sep)

计算打印对象(目录/文件)名称的缩进级别。它已经摆脱了startpath,因为它对于每个列出的文件都很常见,并且看起来很糟糕,所有内容都缩进了+10个标签:) os.sep返回路径分隔符,如' /&#39 ;在Linux上。

关于该错误,请尝试: print('{0}{1}/'.format(indent, os.path.basename(root))) 你有一些例子:http://docs.python.org/2/library/string.html#format-examples可能你的Python不是2.7 +

答案 1 :(得分:2)

下面:

root.replace(startpath, '').count(os.sep)

root是步行的当前目录。

root.replace(startpath, '')

startpath中删除root以获取相对于起始路径的路径。

root.replace(startpath, '').count(os.sep)

在此相对路径中计算os.sep的数量,例如Linux的/。此计数是当前目录相对于起始路径的深度。

相关问题