When working with files in Python, one of the most important concepts to understand is the Current Working Directory (CWD). It determines where your Python script looks for files to read, write, or manipulate unless you provide an absolute file path.
In this post explores what the current working directory is, how to find it, and how to change it using Python’s built-in os and pathlib modules.
Python Current Working Directory
Getting Started
The python current working directory is the folder where your python application is running from. When dealing with files in Python, it is always a good idea to use absolute paths. There are two types of paths in Python concept that is Absolute Paths and Relative Paths.
An absolute path is a path that contains the entire path to the file or directory that you need to access. A relative path is the path that is relative to the working directory location of your application.
However, if you are working with relative paths, you’ll need to understand the concept of the current working directory and how to find or change the current working directory.
The os python module provides a portable way to interact with the operating system. The module is part of the standard Python library and includes methods for finding and changing the current working directory.
In the below we will first see how will access the working directory
Python Get Current Directory
Here below are the code examples for the various ways to access the python current working directory,
- Using OS lib
import os w_dir = os.getcwd() print(w_dir)#python print working directory
- Using pathlib
from pathlib import Path work_dir = Path.cwd() print(work_dir)
- Using os path function
import os print(os.path.dirname(os.path.normpath(__file__)))
Here in the above code the __file__ is a special Python built in variable that contains the path to the currently running script. The os.path.dirname returns the directory name of the given path and the normpath method normalizes a path name by collapsing redundant separators.
Python Set Working Directory
Here in the below, the code example shows how to change python working directory.
import os
print("Current working directory: {0}".format(os.getcwd()))
os.chdir('/tmp')
print("Current working directory: {0}".format(os.getcwd()))
Summary
Here above, we learned that how to access the python current directory( using pythong pwd ) and also we learned change current and print the current directory in Pythong. I hope this article is helpful to you.
Thanks