How to Get Current Directory in Python. Understanding file paths and directory structures is crucial when working with files and directories in any programming language, including Python, one common requirement is to determine the current working directory of a script. This is the directory from which your Python script is being executed.
Table of Contents
Using the ‘os’ Module to Get the Current Directory
Python provides a built-in module named 'os'
which includes utilities to interact with the operating system. 'os.getcwd()'
is a function that returns the current working directory as a string. Here is a complete Python code for getting the current directory.
import os
current_directory = os.getcwd()
print("Current working directory: ",current_directory)
In the above code:
- First, we imported the Python’s os module.
- Then we call the ‘getcwd()’ method to fetch the current working directory.
- At last, we printed the full path of the directory from which the Python script is executed.
Happy Coding & Learning
2 thoughts on “How to Get Current Directory in Python”