Write a program that copies one file to another. Have the program read the file names from user

Here’s a Python program that allows the user to enter the names of the source file and the destination file, and then copies the contents of the source file to the destination file:

def copy_file(source_file, destination_file):
    try:
        with open(source_file, 'r') as source:
            with open(destination_file, 'w') as destination:
                destination.write(source.read())
        print(f"File '{source_file}' successfully copied to '{destination_file}'.")

    except FileNotFoundError:
        print("One or both files not found.")


source_file = input("Enter the name of the source file: ")
destination_file = input("Enter the name of the destination file: ")

copy_file(source_file, destination_file)

 

When you run the program, it will prompt you to enter the name of the source file and the destination file. It then opens both files, reads the contents of the source file using read(), and writes the contents to the destination file using write(). Finally, it prints a success message if the operation is successful. If either of the files is not found, it prints an error message.


Comments

Leave a Reply

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