How to concatenate two files into a new file using Python?


In Python, concatenation is a process that refers to combining two or more strings, lists, or such sequence-like objects into a single object. The concatenation operation when performed is denoted by using the "+" operator.

Concatenating two files into a single file can be a useful process when you want to combine the contents of several files. If you want to merge data from different sources or simply create a consolidated file with aggregated data, Python provides a simple no-frills method to accomplish this task. In this article, we will explore different ways of concatenating two files into a new file using Python, in a step-by-step manner.

Opening the Source Files

Let file1.txt and file2.txt be the two source files that we wish to concatenate.

To start, we need to open the two source files. We can use the open() function, which takes two arguments, namely, the file name and the mode as parameters. In this case, we will open the source files in read mode ('r').

file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')

Reading the Contents of the Files

After opening the above source files, we require to read their contents. This can be done using the read() method, which fetches the entire content of the file as a string.

content1 = file1.read()
content2 = file2.read()

Closing the Source Files

Once the contents of the files have been read, it's standard practice to close them using the close() method. This step makes sure that system resources are freed up or released.

file1.close()
file2.close()

Opening the Destination File

Now, let's open a new file in write mode that will act as the destination file for the concatenated content from the two source files. We use the open() function once more, specifying the file name and the write mode ('w').

destination_file = open('concatenated.txt', 'w')

Writing the Concatenated Content to the Destination File

With the destination file open, we can always write the concatenated content into it using the write() method. Here, we concatenate the source files by simply combining the contents of file1.txt and file2.txt using the '+' operator.

destination_file.write(content1 + content2)

Closing the Destination File

Once the concatenation is done and completed, it's required to close the destination file. This ensures that all the changes are saved.

destination_file.close()

Concatenating Two CSV Files

In this code example, we will showcase how to concatenate two CSV files into a new file using Python. CSV (Comma-Separated Values) files are mostly used for storing tabular data.

import csv
# Open the source CSV files
file1 = open('data1.csv', 'r')
file2 = open('data2.csv', 'r')


# Read the contents of the CSV files
csv_reader1 = csv.reader(file1)
csv_reader2 = csv.reader(file2)

# Create a new CSV file for the concatenated data
destination_file = open('concatenated.csv', 'w', newline='')
csv_writer = csv.writer(destination_file)

# Write the headers to the destination file
headers = next(csv_reader1)
csv_writer.writerow(headers)

# Write the rows from the first CSV file
for row in csv_reader1:
   csv_writer.writerow(row)

# Write the rows from the second CSV file
for row in csv_reader2:
   csv_writer.writerow(row)

# Close all the files
file1.close()
file2.close()
destination_file.close()

  • We import the csv module, which provides functionality for reading and writing CSV files.

  • We open the two source CSV files, data1.csv and data2.csv, in read mode.

  • We create CSV reader objects, csv_reader1 and csv_reader2, for each source file.

  • We open a new CSV file, concatenated.csv, in write mode and create a CSV writer object, csv_writer, for writing the concatenated data.

  • We use the next() function to read the headers from the first CSV file and write them to the destination file.

  • We iterate over the rows in the first CSV file and write each row to the destination file using the writerow() method of the CSV writer.

  • We iterate over the rows in the second CSV file and write each row to the destination file.

  • Finally, we close all the files to release system resources.

Concatenating Two Text Files

In this code example, we will concatenate two text files into a new file using Python. Text files are commonly used for storing textual data.

Let us suppose we have two text files as follows

#text1.txt
I love roses

#text2.txt
I love dahlias too

We, run the following code

# Open the source text files
file1 = open('text1.txt', 'r')
file2 = open('text2.txt', 'r')

# Read the contents of the text files
content1 = file1.read()
content2 = file2.read()

# Close the source text files
file1.close()
file2.close()

# Open the destination file
destination_file = open('concatenated.txt', 'w')

# Write the concatenated content to the destination file
destination_file.write(content1 + content2)
# Close the destination file
destination_file.close()
  • We open the two source text files, text1.txt and text2.txt, in read mode.

  • We read the entire contents of each text file and store them in the variables content1 and content2.

  • We close the source text files using the close() method.

  • We open a new text file, concatenated.txt, in write mode for the destination file.

  • We write the concatenated content of text1.txt and text2.txt to the destination file using the write() method.

  • Finally, we close the destination file to save the changes.

By using these code examples, you can concatenate different types of files, such as CSV files and text files, into a single file using Python.

You have now successfully gained the knowledge of how to concatenate two files into a new file using Python. By following the step-by-step instructions in this article, you can very easily merge the contents of multiple files and create a file with the aggregated content for your specific needs. Python's file-handling functions provide a robust and efficient way to manipulate files and perform various operations. Now you can confidently apply this know-how to concatenate files in your own Python projects.

It is better to use the proper file paths and file names according to your specific file structure. Undertake experimentation with different file formats and explore additional file manipulation functions offered by Python's rich standard library to upgrade your file-handling skills.

Updated on: 17-Jul-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements