[파이썬] shutil `shutil.SameFileError`: 동일한 파일에 대한 예외 처리

In Python, the shutil module provides a high-level interface for file and directory operations. One of the exceptions that can be raised by this module is shutil.SameFileError. This exception is raised when two file paths are found to be referring to the same file.

Understanding shutil.SameFileError

The shutil.SameFileError exception is used to handle situations where two file paths provided as arguments to shutil functions refer to the same file. This could happen, for example, if you try to copy or move a file to the same location where it already exists.

When a SameFileError is raised, it indicates an error condition where the source and destination files are the same. This can help prevent unintentional overwriting or other unexpected behavior.

Handling shutil.SameFileError

To handle shutil.SameFileError, you can use a try-except block to catch the exception and perform the necessary error handling. Here’s an example:

import shutil

try:
    # Perform file operation (e.g., copy, move)
    shutil.copy2('source.txt', 'destination.txt')
except shutil.SameFileError:
    # Handle the SameFileError exception
    print("Error: The source and destination files are the same.")

In the example above, the copy2 function from the shutil module is used to copy the source.txt file to the destination.txt file. If the source and destination files are the same, a SameFileError will be raised, and the code inside the except block will be executed. In this case, it simply prints an error message.

By catching and handling the SameFileError exception, you can ensure that your file operations are safe and avoid potential issues caused by accidentally overwriting files.

Conclusion

When working with the shutil module in Python, it is crucial to be aware of the shutil.SameFileError exception. By handling this exception appropriately, you can avoid unintended consequences and ensure that your file operations proceed smoothly. Be sure to consider this exception, especially when copying or moving files between locations.