[파이썬] shutil 디렉토리 구조 유지하며 다른 위치로 파일 이동하기

In Python, the shutil module provides a convenient way to perform file and directory operations. One common task is moving files from one location to another while maintaining the directory structure. In this blog post, we will explore how to achieve this using the shutil module.

The shutil.move() function

To move files while preserving the directory structure, we can use the shutil.move() function. This function takes two parameters - the source file path and the destination directory path. The source file is moved to the destination directory, and any necessary directories are created to maintain the structure.

Here’s an example usage of the shutil.move() function:

import shutil

source_file = '/path/to/source/file.txt'
destination_dir = '/path/to/destination/'

shutil.move(source_file, destination_dir)

Example Scenario

Let’s consider an example scenario where we have a directory structure like the following:

├── source
│   ├── subdirectory1
│   │   └── file1.txt
│   └── subdirectory2
│       ├── file2.txt
│       └── file3.txt
└── destination

Our goal is to move all the files from the source directory to the destination directory while preserving the directory structure.

Code to Preserve Directory Structure

To achieve this, we can use the os module to iterate through the source directory recursively and move each file to the desired destination using the shutil.move() function.

import os
import shutil

source_dir = '/path/to/source/'
destination_dir = '/path/to/destination/'

for root, dirs, files in os.walk(source_dir):
    for file in files:
        source_file = os.path.join(root, file)
        destination_file = os.path.join(destination_dir, os.path.relpath(source_file, source_dir))
        
        os.makedirs(os.path.dirname(destination_file), exist_ok=True)
        shutil.move(source_file, destination_file)

In the code above, we use the os.walk() function to traverse the source directory recursively. For each file encountered, we construct the corresponding destination file path by joining the destination directory path with the relative path of the source file with respect to the source directory. We also create any necessary directories using os.makedirs() before moving the file using shutil.move().

After running the code, the directory structure will be preserved, and the files will be moved to the destination directory as desired.

Conclusion

In this blog post, we explored how to use the shutil module in Python to move files while preserving the directory structure. By utilizing the shutil.move() function in combination with the os module, we were able to achieve this task effectively. This technique can be useful in various scenarios where maintaining the directory structure is crucial.