我試圖使用this StackOverflow answer中給出的代碼。然而,我不明白什麼線獲取目錄樹形結構
level = root.replace(startpath, '').count(os.sep)
應該這樣做。
而且,當我跑的代碼,就行了
print('{}{}/'.format(indent, os.path.basename(root)))
我試圖使用this StackOverflow answer中給出的代碼。然而,我不明白什麼線獲取目錄樹形結構
level = root.replace(startpath, '').count(os.sep)
應該這樣做。
而且,當我跑的代碼,就行了
print('{}{}/'.format(indent, os.path.basename(root)))
level = root.replace(startpath, '').count(os.sep)
它的計算縮進打印對象(DIR /文件)名的水平,提示錯誤ValueError: zero length field name in format
。它正在擺脫startpath,因爲它對於每個列出的文件都很常見,並且將所有內容縮進+10個標籤都看起來很糟糕:) os.sep在Linux上返回路徑分隔符'/'。
有關錯誤,請嘗試: print('{0}{1}/'.format(indent, os.path.basename(root)))
有你有一些例子:http://docs.python.org/2/library/string.html#format-examples可能是你的Python是不是2.7+
我正在寫相同的答案(即使有相同的鏈接),但你更快/byłeśszybszy;) – furas
這裏:
root.replace(startpath, '').count(os.sep)
的root
是步行的當前目錄。
root.replace(startpath, '')
將刪除root
的startpath
相對於startpath的路徑得到。
root.replace(startpath, '').count(os.sep)
計數os.sep
s時,數例如/
用於Linux,該相對路徑內。此計數是當前目錄相對於startpath的深度。
您正在使用Python 2.6或更低版本,因此請用'{0} {1}'替換'{} {}'。另外,如果你使用的是Windows,那就是'tree'命令。你也可以爲* nix安裝一個。 – Blender