⚡ Python File Transfer 'Project' ⚡

#Python #PythonAutomation

⚡ Python File Transfer 'Project' ⚡

Overview

This is a task assigned to me, and I want to share it with you. As referenced in the subject above the project is about File Transfer with Python, We were tasked to write a Python script that copies files to/from multiple paths with file extension criteria, Also we were tasked to avoid editing the script in future usage, therefor will submit the requested as the below Script code

Script Steps

  • Read values from external CSV files to avoid script editing So in the future, if a non-tech team member is tasked to append some paths will go through the CSV file and just append the values without any edit in the script itself.

  • Ignore the CSV file header ignore the header row

  • Loop on each row in the CSV file.

  • Fetch cells data in variables.

  • Set the condition to only copy the files based on criteria that are mentioned in the CSV file file_match Variable. View the "example.csv" file before going through The Script Code

Script code: ⚡

import csv
import shutil, os
from pathlib import Path

example_file = open('example.csv')  # Open CSV file
example_reader = csv.reader(example_file)  # Reading CSV file

# Loop on each line and ignore Headers
for row in example_reader:
    if example_reader.line_num == 1:
        continue  # Skip the first row, HEADER

    # Print Row number and value
    print('Row #' + str(example_reader.line_num) + ' ' + str(row))

    # Set variables
    print('Set variables...')
    source_path = row[0]  # get the value of the first cell in a variable
    destination_path = row[1]  # get the value of the second cell in a variable

    file_match = row[2]  # get the value of the Third cell in a variable
    print(file_match)

    # Coping files
    print('Coping files...')
    list_files = os.listdir(source_path)  # Listing files/directories in a source_path variable

    # Loop on each file in the list_files
    for file in list_files:
        if file.endswith(file_match):  # match each file end with criteria of file_match variables
            print(f"exist {file}")  # print files list that match the criteria
            source_full_path = source_path + '\\' + file  # Bind source_path with a file name in a variable to use in copy process

            # copying... 
            shutil.copy(source_full_path, destination_path)