Anya Precious
Anya Precious

Reputation: 134

What does os.sep do in this function?

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        # print(dirs)
        if dir!= '.git':
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ' * 4 * (level)
            print('{}{}/'.format(indent, os.path.basename(root)))
            subindent = ' ' * 4 * (level + 1)
            for f in files:
                print('{}{}'.format(subindent, f))

Please I don't understand how the level = root.replace(startpath, '').count(os.sep) works, please I'd appreciate a detailed explanation.

Upvotes: 0

Views: 2480

Answers (1)

wasif
wasif

Reputation: 15498

About os.sep from the Docs

The character used by the operating system to separate pathname components. This is '/' for POSIX and '\' for Windows.

And from help(str.count):

Help on method_descriptor:

count(...)
   S.count(sub[, start[, end]]) -> int

   Return the number of non-overlapping occurrences of substring sub in
   string S[start:end].  Optional arguments start and end are
   interpreted as in slice notation.

So it returns number of path seperators in the path string.

Upvotes: 2

Related Questions