This blog article shows you how to Copy Files from A Predefined List.
This Python script performs the following tasks:
- Imports Required Modules:
- Define Paths:
- csv_file_path: Path to the CSV file (OnlyXmlType3.csv) containing the list of file names to be copied.
- source_directory: Directory where the source XML files are located.
- destination_directory: Directory where the files will be copied to.
- Create Destination Directory:
- Checks if the destination_directory exists. If not, it creates the directory using os.makedirs.
- Read the CSV File:
- Opens the CSV file in read mode.
- Uses csv.reader to read the file line by line.
Also: Update MySQL from Excel using Python
- Process Each Row in the CSV:
- For each row in the CSV, it assumes the file name is in the first column (row[0]).
- Constructs the full path for the source file and the destination file using os.path.join.
- Check and Copy Files:
- Checks if the source file exists using os.path.exists.
- If the source file exists, it copies the file to the destination directory using shutil.copy2 and prints a success message.
- If the source file does not exist, it prints a “File not found” message.
import os
import shutil
import csv
# Define paths
csv_file_path = ‘OnlyXmlType3.csv’
source_directory = r’C:\xml\path_to_save_xml_files’
destination_directory = r’C:\xml\Type3Bulk’
# Create destination directory if it doesn’t exist
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
# Read the CSV file
with open(csv_file_path, mode=’r’) as file:
csv_reader = csv.reader(file)
for row in csv_reader:
file_name = row[0] # Assuming the file names are in the first column
source_file = os.path.join(source_directory, file_name)
destination_file = os.path.join(destination_directory, file_name)
# Check if the source file exists
if os.path.exists(source_file):
# Copy the file
shutil.copy2(source_file, destination_file)
print(f”Copied: {file_name}”)
else:
print(f”File not found: {file_name}”)
This script effectively reads a list of file names from a CSV file and copies those files from a source directory to a destination directory, creating the destination directory if it does not already exist.
Source code download: https://github.com/chanmmn/python/tree/main/2024/XmlTyp3Copy?WT.mc_id=DP-MVP-36769
Reference: https://docs.python.org/3/library/shutil.html?WT.mc_id=DP-MVP-36769