John Bielowski
John Bielowski

Reputation: 309

how to get full path with os.walk function in python

i am using os.walk to find directories, but it does not show the full path

code:

for root, subdirs, files in os.walk(path):
    print(subdirs)

I assign system/ value to path.

Expected output: system/a/a

Output: a

Now i could use glob.glob, but that lists symlinks, and i do not want that

Upvotes: 1

Views: 4369

Answers (3)

Red
Red

Reputation: 27567

Here is what you should do:

import os
for root,subdirs,files in os.walk(path):
    for file in files:
        print(os.path.join(root,file))

Upvotes: 0

le.chris
le.chris

Reputation: 141

To quote the documentation:

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

Putting it together, you get the following:

for root, subdirs, files in os.walk(path):
    for dir in subdirs:
        print(os.path.join(root, dir))

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113955

for root, dirnames, fnames in os.walk(path):
    print("I am looking in", root)
    print("These are the subdirectories:")
    for dirname in dirnames:
        print(os.path.join(root, dirname))

    print("These are the filenames:")
    for fname in fnames:
        print(os.path.join(root, fname))

Upvotes: 6

Related Questions