In this Python tutorial, we will learn how to copy lines from one file to another. This is a common task in file handling, where we may need to duplicate or back up data. Python provides built-in functions to read from one file and write its contents into another. We will use the open() function in read ('r') and write ('w') modes to accomplish this task.
# Function to copy lines from one file to another
def copy_file(source_file, destination_file):
try:
# Open source file in read mode and destination file in write mode
with open(source_file, 'r') as src, open(destination_file, 'w') as dest:
for line in src:
dest.write(line) # Write each line to the destination file
print(f"Contents copied from {source_file} to {destination_file} successfully.")
except FileNotFoundError:
print(f"Error: {source_file} not found.")
# Specify file names
source = "source.txt"
destination = "destination.txt"
# Call the function to copy file content
copy_file(source, destination)
Assume source.txt contains the following lines:
Hello, this is the source file.
It contains multiple lines.
Python is great for file handling!
After running the program, destination.txt will have the same content:
Hello, this is the source file.
It contains multiple lines.
Python is great for file handling!
copy_file):
source_file and destination_file as arguments.source_file in read mode ('r') and destination_file in write mode ('w').with open() statement ensures that files are properly closed after the operation.for loop reads each line from source_file and writes it to destination_file.source_file is not found, a FileNotFoundError is caught, and an error message is displayed."source.txt" and "destination.txt" as parameters.source.txt to destination.txt, maintaining the original content.