In this Python tutorial, we will learn how to copy the file names and contents of 10 files into a single destination file. This is useful for consolidating multiple text files into one, such as log files, reports, or data processing tasks. We will iterate through a list of files, read their content, and write both the file names and content into a single file.
import os
# Function to copy file names and contents into a single file
def merge_files(file_list, destination_file):
try:
with open(destination_file, 'w') as dest:
for file in file_list:
if os.path.exists(file): # Check if the file exists
with open(file, 'r') as src:
dest.write(f"File: {file}\n") # Write file name
dest.write(src.read()) # Write file content
dest.write("\n" + "-" * 40 + "\n") # 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}'.")
except Exception as e:
print(f"An error occurred: {e}")
# List of 10 files to be merged
files_to_merge = [f"file{i}.txt" for i in range(1, 11)] # Example: file1.txt to file10.txt
# Destination file
output_file = "merged_output.txt"
# Call the function to merge files
merge_files(files_to_merge, output_file)
Assume we have 3 sample files (file1.txt
, file2.txt
, file3.txt
) with the following content:
file1.txt
Hello from file 1.
This is some sample text.
file2.txt
This is file 2.
It has multiple lines of text.
file3.txt
File 3 contains important data.
After running the script, merged_output.txt
will contain:
File: file1.txt
Hello from file 1.
This is some sample text.
----------------------------------------
File: file2.txt
This is file 2.
It has multiple lines of text.
----------------------------------------
File: file3.txt
File 3 contains important data.
----------------------------------------
If any file is missing, the script will display a warning.
with open(destination_file, 'w') as dest
opens the target file in write mode.files_to_merge
) is passed to the function.os.path.exists(file)
ensures that only existing files are processed.dest.write(f"File: {file}\n")
writes the filename to distinguish sections.dest.write(src.read())
copies the content of the file."-" * 40 + "\n"
) is added for clarity.try-except
block ensures that any unexpected errors are caught and displayed.This approach efficiently merges multiple files into one, preserving both filenames and content. It can be adapted for different file types or extended for batch processing tasks.