[파이썬] shutil 특정 시간대의 파일만 선택하여 복사 또는 이동하기

Introduction

In this blog post, we will explore how to use the shutil module in Python to selectively copy or move files based on a specific time range. The shutil module provides a high-level interface for file operations, making it convenient to manipulate files and directories in Python.

Selecting Files by Time Using os module

Before we dive into using shutil, let’s first understand how to select files based on a specific time range using the os module. The os module provides several functions for interacting with the operating system, including file operations.

import os
import datetime

def get_files_in_time_range(directory, start_time, end_time):
    files_in_range = []

    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            file_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
            
            if start_time <= file_time <= end_time:
                files_in_range.append(file_path)

    return files_in_range

In the above code, the get_files_in_time_range function takes three parameters: directory (the root directory to search for files), start_time, and end_time (the time range to filter files). It recursively walks through the given directory, and for each file encountered, it retrieves the file’s last modification time using os.path.getmtime. If the file’s time falls within the specified range, it appends the file path to the files_in_range list. Finally, the function returns the list of files within the specified time range.

Copying or Moving Files Using shutil module

Once we have the list of files within the desired time range, we can use the shutil module to copy or move those files to a new location. The shutil module provides functions like shutil.copy and shutil.move for this purpose.

import shutil

def copy_files(files, destination):
    for file in files:
        shutil.copy(file, destination)

def move_files(files, destination):
    for file in files:
        shutil.move(file, destination)

The copy_files function takes the list of files as well as a destination directory path. It iterates over each file in the list and copies it to the specified destination using shutil.copy.

Similarly, the move_files function takes the list of files and the destination directory. It iterates over each file and moves it to the destination directory using shutil.move.

Conclusion

Using the shutil module in combination with the os module, we can easily select files based on a specific time range and perform operations like copying or moving them to another directory. This can be useful in various scenarios, such as organizing files, creating backups, or archiving data. By understanding the capabilities of these modules, you can efficiently manage and manipulate files in Python.