Home > Mobile >  How to show directory name only, instead of whole path in os.walk
How to show directory name only, instead of whole path in os.walk

Time:09-26

So if I want to print only the directory name instead of whole base path, is there any tricks to achieve it :)

import os

for root, dirs, files in os.walk("/home/lungsang/Desktop/levelpack-UI/content/A0/1 docx-raw"):
    print(root)

Here I get the result :

/home/ubuntu/levelpack-UI/content/A0/1 docx-raw

My desired result : only the directory name only.

1 docx-raw

CodePudding user response:

Standard os.path functionality:

print(os.path.split(root)[1])

Seems too trivial for the stackoverflow I guess. Anyway...

CodePudding user response:

The simplest solution is print(root.split("/")[-1])

CodePudding user response:

This one worked for me. thnx !

import os

out = os.path.basename("/home/ubuntu/levelpack-UI/content/A0/1 docx-raw")
print(out)
  • Related