Python Fileoperations: Copy Lines from one File to nother

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.


Code Example:

# 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)

Output (Example Scenario):

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!

Code Explanation:

  1. Function Definition (copy_file):
    • The function takes source_file and destination_file as arguments.
    • It attempts to open source_file in read mode ('r') and destination_file in write mode ('w').
  2. Reading and Writing Lines:
    • Using a with open() statement ensures that files are properly closed after the operation.
    • The for loop reads each line from source_file and writes it to destination_file.
  3. Error Handling:
    • If the source_file is not found, a FileNotFoundError is caught, and an error message is displayed.
  4. Execution:
    • The function is called with "source.txt" and "destination.txt" as parameters.
    • It copies all lines from source.txt to destination.txt, maintaining the original content.