0% found this document useful (0 votes)
16 views1 page

Python Filehandling

The document defines a Python function that copies files from a source directory to a destination directory based on specified file types and size limits. It creates the destination directory if it doesn't exist and filters files according to the provided criteria before copying. The function is then called with specific parameters for source and destination paths, file types, and maximum file size.

Uploaded by

shaikbajan1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

Python Filehandling

The document defines a Python function that copies files from a source directory to a destination directory based on specified file types and size limits. It creates the destination directory if it doesn't exist and filters files according to the provided criteria before copying. The function is then called with specific parameters for source and destination paths, file types, and maximum file size.

Uploaded by

shaikbajan1995
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Define the function

import os
import shutil

def copy_files_with_filters(sourcepath, destinationpath, file_types=None,


size_limit_mb=None):
[Link](destinationpath, exist_ok=True)
size_limit_bytes = size_limit_mb * 1024 * 1024 if size_limit_mb else None

for file_name in [Link](sourcepath):


file_path = [Link](sourcepath, file_name)

if not [Link](file_path):
continue

if file_types and not file_name.lower().endswith(tuple(file_types)):


continue

file_size = [Link](file_path)
if size_limit_bytes and file_size > size_limit_bytes:
continue

destination_file_path = [Link](destinationpath, file_name)


[Link](file_path, destination_file_path)
print(f"Copied: {file_name}")

# Call the function


source_path = "c:/test"
destination_path = "c:/destination"
file_types_to_filter = ['.txt', '.csv']
max_file_size_mb = 5

copy_files_with_filters(source_path, destination_path, file_types_to_filter,


max_file_size_mb)

You might also like