In this advanced Python example, we will merge multiple text files into a single file while also including additional metadata such as:
This can be useful for log management, report consolidation, or data processing tasks where tracking file information is essential.
import os
import datetime
# Function to merge multiple files with metadata
def merge_files_with_metadata(file_list, destination_file):
try:
with open(destination_file, 'w') as dest:
for file in file_list:
if os.path.exists(file): # Check if file exists
file_size = os.path.getsize(file) # Get file size in bytes
last_modified = os.path.getmtime(file) # Get last modified timestamp
timestamp = datetime.datetime.fromtimestamp(last_modified).strftime('%Y-%m-%d %H:%M:%S')
# Write metadata to the output file
dest.write(f"File Name: {file}\n")
dest.write(f"File Size: {file_size} bytes\n")
dest.write(f"Last Modified: {timestamp}\n")
dest.write("-" * 50 + "\n")
# Read and write the content of the file
with open(file, 'r') as src:
dest.write(src.read())
dest.write("\n" + "=" * 50 + "\n\n") # Add separator
else:
print(f"Warning: {file} does not exist and will be skipped.")
print(f"Contents of {len(file_list)} files copied to '{destination_file}' with metadata.")
except Exception as e:
print(f"An error occurred: {e}")
# List of files to be merged
files_to_merge = [f"file{i}.txt" for i in range(1, 6)] # Example: file1.txt to file5.txt
# Destination file
output_file = "merged_output_with_metadata.txt"
# Call the function to merge files with metadata
merge_files_with_metadata(files_to_merge, output_file)
If we have three sample files (file1.txt
, file2.txt
, file3.txt
) with the following metadata:
file1.txt
: 1024 bytes, last modified 2025-03-15 10:30:00file2.txt
: 2048 bytes, last modified 2025-03-16 14:45:00file3.txt
: 512 bytes, last modified 2025-03-16 16:00:00After running the script, merged_output_with_metadata.txt
will contain:
File Name: file1.txt
File Size: 1024 bytes
Last Modified: 2025-03-15 10:30:00
--------------------------------------------------
[File 1 content goes here]
==================================================
File Name: file2.txt
File Size: 2048 bytes
Last Modified: 2025-03-16 14:45:00
--------------------------------------------------
[File 2 content goes here]
==================================================
File Name: file3.txt
File Size: 512 bytes
Last Modified: 2025-03-16 16:00:00
--------------------------------------------------
[File 3 content goes here]
==================================================
'w'
) to ensure data is written from scratch.os.path.exists(file)
.os.path.getsize(file)
: Retrieves the file size in bytes.os.path.getmtime(file)
: Retrieves the last modified timestamp (converted to a readable format using datetime
)."-" * 50
and "=" * 50"
) is added for better readability.✅ Preserves file metadata (size & last modified time).
✅ Handles missing files gracefully (skips and warns).
✅ Enhances readability by separating content and metadata.
✅ Scalable for large file lists (handles multiple files efficiently).
This script is particularly useful for log file consolidation, backup reports, or automated data management systems! 🚀