Reputation: 4339
I was trying to use the code given in this StackOverflow answer. However, I don't understand what the line
level = root.replace(startpath, '').count(os.sep)
is supposed to do.
Also, when I ran the code, it gave an error ValueError: zero length field name in format
on the line
print('{}{}/'.format(indent, os.path.basename(root)))
Upvotes: 1
Views: 276
Reputation: 98108
Here:
root.replace(startpath, '').count(os.sep)
The root
is the current directory of the walk.
root.replace(startpath, '')
removes the startpath
from the root
to get the path relative to the startpath.
root.replace(startpath, '').count(os.sep)
counts the number of os.sep
s, for example /
for Linux, within this relative path. This count is the depth of the current directory relative to the startpath.
Upvotes: 2
Reputation: 1178
level = root.replace(startpath, '').count(os.sep)
It's calculating level of indentation for printing object (dir/file) name. It's getting rid of startpath as it's common for every listed file and it would look bad to have everything indented by +10 tabs :) os.sep returns path separator like '/' on Linux.
About that error, try:
print('{0}{1}/'.format(indent, os.path.basename(root)))
There you have some examples: http://docs.python.org/2/library/string.html#format-examples Probably your Python is not 2.7+
Upvotes: 2