Python Program to Copy One File to Another File

This Python program is designed to copy the contents of one file to another file. It provides a simple and efficient way to duplicate the content from a source file to a destination file. The program handles potential errors such as missing source files or unexpected issues during the copying process.

Problem Statement

By using this program, users can conveniently replicate the content of a file, which can be particularly useful for tasks like data backup or creating duplicates of important documents.

Python Program to Copy One File to Another File

def copy_file(source_file, destination_file):
    try:
        with open(source_file, 'r') as source:
            with open(destination_file, 'w') as destination:
                for line in source:
                    destination.write(line)
        print("File copied successfully!")
    except FileNotFoundError:
        print("Source file not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

def main():
    print("File Copy Program\n")
    source_file = input("Enter the source file name: ")
    destination_file = input("Enter the destination file name: ")
    copy_file(source_file, destination_file)

if __name__ == "__main__":
    main()

How it works

  1. The program defines a function copy_file that takes two arguments: source_file and destination_file.
  2. Inside the function, it attempts to open the source file in read mode ('r') and the destination file in write mode ('w').
  3. It then iterates through each line of the source file and writes it to the destination file.
  4. The main function is defined to interact with the user. It prompts the user to input the source and destination file names.
  5. The copy_file function is called with the provided file names.
  6. If the source file is not found, a FileNotFoundError is caught and an appropriate message is displayed. Other exceptions are caught using a generic Exception and their messages are displayed.

Input / Output

Python Program to Copy One File to Another File

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...