How to get Curent Working Directory Using Python
When addressing files in directories in Python, it’s always a decent idea to use absolute paths. However, if you’re working with relative paths, you’ll must understand the concept of the present working directory and the way to seek out or change the present working directory. An absolute path specifies a file or directory location ranging from the basis directory, while the relative path begins from this working directory.
When you run a Python script, the present working directory is ready to the directory from which the script is executed.
The os python module provides a transportable thanks to interact with the software system. The module is an element of the quality Python library and includes methods for locating and changing this working directory
Python Get current working directory with os.getcwd()
import os
w_dir = os.getcwd()
print(w_dir)
OUTPUT
/janbodnar/Documents/prog/python/getcwd
Get current working directory with Path.cwd
from pathlib import Path
work_dir = Path.cwd()
print(work_dir)
OUTPUT
/janbodnar/Documents/prog/python/getcwd
Get current working directory with os.path
import os
print(os.path.dirname(os.path.normpath(__file__)))
print(os.path.abspath('.'))
OUTPUT
/janbodnar/Documents/prog/python/getcwd
Changing the Current Working Directory in Python
# Import the os module import os # Print the current working directory print("Current working directory: {0}".format(os.getcwd())) # Change the current working directory os.chdir('/tmp') # Print the current working directory print("Current working directory: {0}".format(os.getcwd()))
OUTPUT
Current working directory: /home/users/Desktop
Current working directory: /tmp