Python
About Lesson

Merge two text files into a third file

# 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)

Explanation

  • It opens a file named “file1.txt” in read mode and assigns it to the variable file1.
  • It reads the content of “file1.txt” and stores it in the variable text1.
  • It opens another file named “file2.txt” in read mode and assigns it to the variable file2.
  • It reads the content of “file2.txt” and stores it in the variable text2.
  • It opens a third file named “file3.txt” in write mode and assigns it to the variable file3.
  • It writes the concatenation of text1, the string "n" (which seems to be a typo for "n" representing a newline character), and text2 into “file3.txt”.

 

Here’s a breakdown of each part:

# Open a file1 in read mode
with open("file1.txt", "r") as file1:
# Read its content
text1 = file1.read()

 

This block of code opens “file1.txt” in read mode using the open() function and assigns the file object to the variable file1. It then reads the content of file1 using the .read() method and stores it in the variable text1.

# Open a file2 in read mode
with open("file2.txt", "r") as file2:
# Read its content
text2 = file2.read()

 

This block of code does the same thing as the previous block but for “file2.txt”. It opens the file, reads its content, and stores it in the variable text2.

# Open a file3 in write mode
with open("file3.txt", "w") as file3:
# Write all the content in file3
file3.write(text1+"n"+text2)
 

This block of code opens “file3.txt” in write mode, truncating the file if it already exists, and creating it if it doesn’t. Then it writes the concatenation of text1, the string "n" (which should likely be "n" for a newline character), and text2 into “file3.txt”.

The above code reads the contents of two files (“file1.txt” and “file2.txt”) and concatenates them together with a newline character in between, then writes the combined content into a third file (“file3.txt”).

 

Mode Name Description
r Read Opens a file for reading, and 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.