Bootstrap FreeKB - Python (Scripting) - dirname basename and present working directory (pwd)
Python (Scripting) - dirname basename and present working directory (pwd)

Updated:   |  Python (Scripting) articles

os.path.basename can be used to get the basename from a path and os.path.dirname can be used to get the directory from a path.

You will typically want to also use os.path.exists to determine if the file or directory exists.

#!/usr/bin/python3
import os.path
if os.path.exists("/usr/local/foo.txt") == True:
  dirname  = os.path.dirname("/usr/local/foo.txt")
  basename = os.path.basename("/usr/local/foo.txt")
  print(f"dirname = {dirname}")
  print(f"basename = {basename}")

 

Which should print the following.

dirname = /usr/local
basename = foo.txt

 

You could also use os.path.realpath to get the present working directory.

#!/usr/bin/python3
import os.path
pwd = os.path.dirname(os.path.realpath(__file__))
print(f"pwd = {pwd}")

 

Which should return something like this.

pwd = /home/john.doe

 

Or getcwd (get current working directory) can be used.

#!/usr/bin/python3
import os
getcwd = os.getcwd()
print(f"getcwd = {getcwd}")

 

Which should return something like this.

getcwd = /home/john.doe



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 315b9f in the box below so that we can be sure you are a human.