In this article we will show you the solution of get current directory python, the use of absolute paths is always recommended when working with files in directories in Python.
The current working directory must be understood if you're working with relative paths, as well as how to find or change it.
The relative path refers to a location from the current directory to the root directory, while the absolute path refers to the location from the current directory to the root directory.
A Python script is run from the directory from which it was executed, and the current working directory is set accordingly.
We will now discuss the idea of how to get the current directory in python with an example.
Step By Step Guide On Get Current Directory Python :-
import os path = '/var/tc' try: os.chdir(path) print("our current working directory: {0}".format(os.getcwd())) except FileNotFoundError: print("directory: {0} does not exists".format(path)) except NotADirectoryError: print("{0} is not directory".format(path)) except PermissionError: print("You do not have to change permissions to {0}".format(path))
- Our first step is to import os, which provides a means of interacting with the operating system.
- Our current working directory can be changed by storing the path to it in the path variable.
- As soon as we attempt to change the working directory, the try-except block is used to handle any possible errors.
- The os.chdir() method in the try block changes the current working directory to the specified path.
- Our program uses the os.getcwd() method to get the current working directory and prints it to the console using the format() function.
- Our except block handles three different types of errors that could occur while attempting to change the working directory, including FileNotFoundError if the directory doesn't exist. In the case of an error, the specified path cannot be used as a directory. In the case of an error where we do not have permission to change a directory to the specified one, we will get a permission error.
- With the format() method, we print a message describing the error to the console if one occurs.
Conclusion :-
As a result, we have successfully learned how to get the current directory in python with an example.
The current working directory is obtained using os.getcwd(), and the current working directory is changed using os.chdir(path).
I hope this article on get current directory python helps you and the steps and method mentioned above are easy to follow and implement.