Categories
Python Answers

How to concatenate text files in Python?

Spread the love

Sometimes, we want to concatenate text files in Python.

In this article, we’ll look at how to concatenate text files in Python.

How to concatenate text files in Python?

To concatenate text files in Python, we can use the with statement and the open function.

For instance, we write:

filenames = ['file1.txt', 'file2.txt']
with open('file.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

We have the filenames list that has the paths of the files we want to join together.

Then we call open with the file we want to write the combined file contents to.

In the with block, we have a for loop to loop through the filenames and open each fname entry with open.

Then we loop through each line of each open file and call outfile.write to write each line in the input files.

Conclusion

To concatenate text files in Python, we can use the with statement and the open function.

Leave a Reply

Your email address will not be published. Required fields are marked *