[파이썬] 파일의 디렉토리 이름 변경

Python provides a powerful and straightforward way to rename directories using the os module. In this blog post, we will explore how to rename a directory in Python and understand the steps involved in accomplishing this task.

Renaming a Directory

To rename a directory in Python, we can use the os.rename() function. This function takes two arguments: the current name of the directory and the new name we want to give it. The code snippet below demonstrates the process:

import os

# Specify the current directory name and the new desired name
current_name = 'old_directory_name'
new_name = 'new_directory_name'

# Rename the directory
os.rename(current_name, new_name)

Note: Make sure that the current directory exists and that the new name is not already being used by a different directory.

Handling Errors

When performing directory renaming, it’s important to handle any potential errors that may arise. We can achieve this by using a try-except block. The example below illustrates how to implement error handling while renaming a directory:

import os

def rename_directory(current_name, new_name):
    try:
        os.rename(current_name, new_name)
        print(f"Successfully renamed directory: {current_name} -> {new_name}")
    except OSError as e:
        print(f"Error renaming directory: {current_name} -> {new_name}")
        print(f"Error details: {e}")

# Specify the current directory name and the new desired name
current_name = 'old_directory_name'
new_name = 'new_directory_name'

# Rename the directory with error handling
rename_directory(current_name, new_name)

Summary

Renaming directories is a common task during file management in Python. The os.rename() function provides an efficient and easy-to-use method for accomplishing this task. Additionally, implementing error handling enhances the robustness of our code.

Remember to always test your code thoroughly before renaming important directories, and ensure that you have appropriate backup systems in place.

I hope you found this blog post helpful! Stay tuned for more Python-related content.