[파이썬] os 디렉토리 변경: `os.chdir()`

Changing the current working directory can be helpful when you want to navigate to a different directory to perform certain tasks or access files. The os.chdir() function takes a single argument, which is the path to the directory you want to change to.

import os

# Get the current working directory
current_dir = os.getcwd()
print("Current directory:", current_dir)

# Change the directory to a new path
new_dir = '/path/to/new/directory'
os.chdir(new_dir)

# Verify the directory has changed
updated_dir = os.getcwd()
print("Updated directory:", updated_dir)

In the example above, we first use the os.getcwd() function to get the current working directory and print it out. Then, we use os.chdir() to change the directory to a new path specified by /path/to/new/directory. Finally, we use os.getcwd() again to see the updated working directory.

It is important to note that when using os.chdir(), the new directory path should be a valid path on your operating system. Otherwise, an error will occur. Additionally, make sure you have the necessary permissions to access the directory.

Changing the directory using os.chdir() can be particularly useful when working with file I/O, running scripts that require specific file locations, or organizing your project directories.

Remember, the os module in Python offers various functions to interact with the operating system, and os.chdir() is just one of the many capabilities it provides. Be sure to explore the module’s documentation to fully utilize its potential.