28
How to get current directory in Python?
ItsMyCode |
In this article, we will take a look at how to get current directory in Python. The current directory is nothing but your working directory from which your script is getting executed.
The os module has a getcwd()
function using which we can find out the absolute path of the working directory.
*Syntax: * os.getcwd()
Parameter: None
Return Value: Returns the string which contains the absolute path of the current working directory.
Below is an example to print the current working directory in Python
# Python program get current working directory using os.getcwd()
# importing os module
import os
# Get the current directory path
current_directory = os.getcwd()
# Print the current working directory
print("Current working directory:", current_directory)
Output
Current working directory: C:\Projects\Tryouts
If you want to get the path of the current script file, you could use a variable ` __file_ `_ and pass it to _the _realpath
method of the os.path module.
Example to get the path of the current script file
# Python program get current working directory using os.getcwd()
# importing os module
import os
# Get the current directory path
current_directory = os.getcwd()
# Print the current working directory
print("Current working directory:", current_directory)
# Get the script path and the file name
foldername = os.path.basename(current_directory)
scriptpath = os.path.realpath( __file__ )
# Print the script file absolute path
print("Script file path is : " + scriptpath)
Output
Current working directory: C:\Projects\Tryouts
Script path is : C:\Projects\Tryouts\main.py
If you want to change the current working directory in Python, use the chrdir() method.
Syntax: os.chdir(path)
Parameters:
path: The path of the new directory in the string format.
Returns: Doesn’t return any value
Example to change 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('/Projects')
# Print the current working directory
print("New Current working directory: {0}".format(os.getcwd()))
Output
Current working directory: C:\Projects\Tryouts
New Current working directory: C:\Projects
To get the current working directory in Python, use the os module function os.getcwd()
, and if you want to change the current directory, use the os.chrdir()
method.
The post How to get current directory in Python? appeared first on ItsMyCode.
28