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 open each file and call write to write the contents of each file to a file.

For instance, we write

filenames = [
    "file1.txt",
    "file2.txt",
    # ...
]
with open("path/to/output/file", "w") as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

to call open to open the output file with write permission

Then we loop through the file names strings in filenames with a for loop.

In the loop, we call open to open the input file.

And then we loop through each line with another for loop.

In it, we call outfile.write to write the line into the output file.

Conclusion

To concatenate text files in Python, we can open each file and call write to write the contents of each file to a file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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