[파이썬] 파일의 디렉토리 내 파일 다운로드

Python provides several ways to download files from a directory. In this blog post, we will explore different methods to download files from a directory using Python.

Method 1: Using the ‘os’ module

You can use the os module in Python to navigate through directories and download files. Here’s an example:

import os
import shutil

def download_files(directory):
    for filename in os.listdir(directory):
        if os.path.isfile(os.path.join(directory, filename)):
            shutil.copy(os.path.join(directory, filename), os.getcwd())
            print(f"Downloaded: {filename}")
    print("Download complete.")

# Specify the directory where the files are located
directory_to_download = "/path/to/directory"

# Call the function to download files from the directory
download_files(directory_to_download)

This code snippet uses the os.listdir() function to iterate over all the files in the specified directory. Then, it checks if each item is a file using os.path.isfile(). If it is a file, it uses shutil.copy() to copy the file from the directory to the current working directory (os.getcwd()). Finally, it prints a message for each downloaded file and a completion message.

Method 2: Using the ‘glob’ module

The glob module provides a more streamlined way of finding files based on patterns. You can use it to download files matching specific criteria. Here’s an example:

import glob
import shutil

def download_files(directory, file_extension):
    files_to_download = glob.glob(f"{directory}/*{file_extension}")
    for file_path in files_to_download:
        shutil.copy(file_path, os.getcwd())
        print(f"Downloaded: {file_path}")
    print("Download complete.")

# Specify the directory and file extension
directory_to_download = "/path/to/directory"
file_extension_to_download = ".txt"

# Call the function to download files from the directory
download_files(directory_to_download, file_extension_to_download)

This code snippet uses the glob.glob() function to find all files in the specified directory with the specified file extension. Then, it uses shutil.copy() to copy each file to the current working directory. It also prints a message for each downloaded file and a completion message.

These methods provide a basic way to download files from a directory in Python. You can customize and enhance them based on your specific requirements. Remember to import the required modules and specify the correct directory path and file extension.

I hope this blog post helps you in downloading files from a directory using Python. Happy coding!