Merge two text file into third
# Open a file1 in read mode
with open("file1.txt", "r") as file1:
# Read its content
text1 = file1.read()
# Open a file2 in read mode
with open("file2.txt", "r") as file2:
# Read its content
text2 = file2.read()
# Open a file3 in write mode
with open("file3.txt", "w") as file3:
# Write all the content in file3
file3.write(text1+"\n"+text2)
Explaination
In above program, we have read two files (file1.txt
and file2.txt
) using open()
function and stores it's output into respective variables i.e. text1
and text2
.
Finally, we have copied the content of both variables into file3.txt
.
Mode | Name | Description |
---|---|---|
r
|
Read | Opens a file for reading, returns an error if the file does not exist. It is a default mode. |
w
|
Write | Opens a file for writing a file, creates the file if it does not exist or deletes the content of the file if it exists. |