Open In App

Change current working directory with Python

Last Updated : 07 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.
To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
Note: The current working directory is the folder in which the Python script is operating.
 

Syntax: os.chdir(path)
Parameters: 
path: A complete path of the directory to be changed to the new directory path.
Returns: Doesn’t return any value 
 

Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation. 
 

Python3




# Python program to change the
# current working directory
 
 
import os
 
# Function to Get the current
# working directory
def current_path():
    print("Current working directory before")
    print(os.getcwd())
    print()
 
 
# Driver's code
# Printing CWD before
current_path()
 
# Changing the CWD
os.chdir('../')
 
# Printing CWD after
current_path()


Output: 
 

Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg

Current working directory after
C:\Users\Nikhil Aggarwal\Desktop

Example #2: Handling the errors while changing the directory. 
 

Python3




# Python program to change the
# current working directory
 
 
# importing all necessary libraries
import sys, os
   
# initial directory
cwd = os.getcwd()
   
# some non existing directory
fd = 'false_dir/temp'
   
# trying to insert to false directory
try:
    print("Inserting inside-", os.getcwd())
    os.chdir(fd)
       
# Caching the exception    
except:
    print("Something wrong with specified directory. Exception- ")
    print(sys.exc_info())
             
# handling with finally          
finally:
    print()
    print("Restoring the path")
    os.chdir(cwd)
    print("Current directory is-", os.getcwd())


Output:
 

Inserting inside- C:\Users\Nikhil Aggarwal\Desktop\gfg
Something wrong with specified directory. Exception- 
(<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)
Restoring the path 
Current directory is- C:\Users\Nikhil Aggarwal\Desktop\gfg 
 

 



Previous Article
Next Article

Similar Reads

Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
How to Get directory of Current Script in Python?
A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about va
4 min read
Get Current directory in Python
In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The concept of the Current Working Directory (CWD) becomes
3 min read
How to Change the Owner of a Directory Using Python
We can change who owns a file or directory by using the pwd, grp, and os modules. The uid module is used to change the owner, get the group ID from the group name string, and get the user ID from the user name. In this article, we will see how to change the owner of a directory using Python. Change the Owner of a Directory Using PythonBelow are the
5 min read
Rename all file names in your directory using Python
Given multiple files in a directory having different names, the task is to rename all those files in sorted order. We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating system-dependent functionality. We can go to the cu
1 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
Create a directory in Python
The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. All functions in os module raise OSError in
6 min read
Delete a directory or file using Python
In this article, we will cover how to delete (remove) files and directories in Python. Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Various methods provided by Python are - Using os.remove()Using os.rmdir()Using shutil.rmtree()Using pathlib.Path(empty_dir_path).
7 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Python: Check if a File or Directory Exists
Sometimes the need to check if the folder exists in python, and check whether a directory or file exists becomes important because maybe you want to prevent overwriting the already existing file, or maybe you want to make sure that the file is available or not before loading it. So to check how to check if a Directory Exists without exceptions in P
5 min read