Examples
- How to Create Directory in Python? New and If Not Exists
- How to Change Directory in Python? Change Current Working Directory
- How to Get Current Working Directory in Python?
- How to Remove Directory in Python? (Empty & With Files)
- How to Copy Directory in Python? Program With Examples
- How to Open Directory in Python? Program & Example
- How to Read All Files in Directory in Python? (All Types of Files)
- How to Copy File in Python From One Directory to Another? (With and Without shutil)
- Python File Append Program (Append to File)
- How to Read Text File in Python Line by Line? (3 Ways)
- How to Get File Name From File Path in Python?
- Get Number of Lines in File in Python (Line Count)
- How to Get Size of File in Python? (File Size Program)
How to Change Directory in Python? Change Current Working Directory
Changing the current working directory in Python is a common task when working with file systems and organizing files. The current working directory is the directory from which your Python script is currently running.
In this post, we will learn how to change the directory in Python using the os module. This module provides functions for interacting with the operating system, including file system operations. With the os.chdir() function, you can easily change the current working directory to a specified path.
Change Current Working Directory in Python
Code
import os
# Specify the directory path
new_directory = "/path/to/new_directory"
# Change the current working directory
os.chdir(new_directory)
# Print the current working directory
print("Current working directory:", os.getcwd())
Output
..
Explanation
In this program, the os.chdir() function is used to change the current working directory. You need to provide the desired path to the new_directory variable. Replace "/path/to/new_directory" with the actual path you want to change to.
After executing os.chdir(), the current working directory will be updated to the specified path. You can verify the change by printing the current working directory using the os.getcwd() function.
Please note: The specified path should be a valid directory path on your system. If the directory does not exist or there are any permission issues, an error may occur. Make sure to handle such cases appropriately in your code.