How to Copy the Contents of a File in Python?

Estimated read time 1 min read

To copy the contents of a file in Python, you can read the contents of the source file and write them to a new file. Here’s an example:

# Open the source file for reading
with open('source.txt', 'r') as f_source:
    # Read the contents of the source file
    contents = f_source.read()

# Open the destination file for writing
with open('destination.txt', 'w') as f_destination:
    # Write the contents to the destination file
    f_destination.write(contents)

In this example, we first open the source file source.txt for reading using the with statement. We then read the contents of the file using the read() method and store them in the contents variable.

Next, we open the destination file destination.txt for writing using the with statement. We then write the contents of the contents variable to the destination file using the write() method.

After the with blocks are exited, both files are automatically closed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply