How can I use the Python set working directory functionality to change the directory during runtime?

How can I set the current working directory in Python?

I want to know how to set the current working directory in Python. How can I use the Python set working directory functionality to change the directory during runtime?

Using os.chdir() The os module provides a chdir() method that can be used to change the current working directory. Here’s how you can use it:

import os
os.chdir('/path/to/directory')
print("Current Working Directory:", os.getcwd())

This will set the working directory to the specified path.

Using pathlib.Path (Python 3.4 and above) The pathlib module provides an object-oriented approach to dealing with paths. You can change the working directory using Path.chdir().

from pathlib import Path
Path('/path/to/directory').chdir()
print("Current Working Directory:", Path.cwd())

This sets the current working directory to the specified path in a clean and readable way.

Using os.makedirs() (with a check) If you’re not sure if the directory exists and want to ensure it exists before changing the working directory, you can use os.makedirs():

import os
directory = '/path/to/directory'
if not os.path.exists(directory):
    os.makedirs(directory)
os.chdir(directory)
print("Current Working Directory:", os.getcwd())

This creates the directory if it doesn’t exist and then changes the working directory to it.