You can get the current working directory in Python using the os.getcwd()
function. This function returns a string representing the absolute path of the current working directory.
Here's a simple example:
import os
current_directory = os.getcwd()
print(current_directory)
This code will print the absolute path of the directory where the Python script is running.
Practical Insights:
- The
os.getcwd()
function is useful for tasks like reading and writing files relative to the current directory. - You can use the
os.chdir()
function to change the current working directory.
Example:
Let's say you have a script named my_script.py
in a directory called my_project
. If you run this script, os.getcwd()
will return the path to my_project
.
Code Example:
# my_script.py
import os
print(os.getcwd()) # Output: /path/to/my_project