skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

    This one worked for me. thnx !

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

  2. Standard os.path functionality:

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

    Seems too trivial for the stackoverflow I guess. Anyway…

    Login or Signup to reply.
  3. The simplest solution is print(root.split("/")[-1])

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search