[파이썬] 파일의 디렉토리 내 파일 복구

Have you ever accidentally deleted a file or lost important data and wished there was a way to recover it? Well, in this blog post, we will explore how to recover files within a directory using the power of Python!

Prerequisites

Before we dive into the code, let’s make sure we have the necessary prerequisites in place:

  1. Python installed on your machine (version 3.0 or above)
  2. Basic understanding of file handling in Python

Steps to Recover Files within a Directory

  1. Retrieve the list of deleted files within the directory:
import os

def get_deleted_files(directory):
    deleted_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            if not os.path.exists(file_path):
                deleted_files.append(file_path)
    return deleted_files
  1. Recover the deleted files:
import shutil

def recover_files(deleted_files, target_directory):
    for file_path in deleted_files:
        file_name = os.path.basename(file_path)
        target_path = os.path.join(target_directory, file_name)
        shutil.copy2(file_path, target_path)
  1. Put it all together:
def file_recovery(directory, target_directory):
    deleted_files = get_deleted_files(directory)
    recover_files(deleted_files, target_directory)

Usage Example

Let’s say you accidentally deleted some files in the “documents” directory, and you want to recover them to a new directory called “recovered_files”. Here’s how you would use the file_recovery function:

directory = "documents"
target_directory = "recovered_files"
file_recovery(directory, target_directory)

This will go through the “documents” directory, find the deleted files, and recover them to the “recovered_files” directory.

Conclusion

In this blog post, we explored how to recover files within a directory using Python. With just a few lines of code, you can easily retrieve and recover deleted files. Remember to always proceed with caution when performing file recovery operations and ensure you have a backup of important data.

Thank you for reading, and happy file recovery in Python!