You can copy the contents of one text file to another text file using Python by opening both files and reading the contents of the source file and writing them to the destination file. Here’s an example:
# Open the source file for reading
with open('source.txt', 'r') as source_file:
# Read the contents of the source file
file_contents = source_file.read()
# Open the destination file for writing
with open('destination.txt', 'w') as destination_file:
# Write the contents of the source file to the destination file
destination_file.write(file_contents)
In this example, we first open the source file 'source.txt'
in read mode using a with
statement. We read the contents of the file using the read()
method and store them in a variable called file_contents
.
Next, we open the destination file 'destination.txt'
in write mode using another with
statement. We write the contents of the source file to the destination file using the write()
method.
Note that this example will overwrite any existing content in the destination file. If you want to append the contents of the source file to the destination file instead of overwriting it, you can open the destination file in append mode by changing the second open()
call to open('destination.txt', 'a')
.
+ There are no comments
Add yours