You can concatenate files in Python easily. To concatenate two files, you can read the content from both files, store the contents in strings, concatenate the strings and then write the final string to a new file.
with open('file1.txt') as f:
f1 = f.read()
with open('file2.txt') as f:
f2 = f.read()
f3 = f1 + "n" + f2
with open('file3.txt','w') as f:
f.write(f3)
When working with files in Python, the ability to change or manipulate the contents of these files can be useful.
One such operation is being able to combine two files into one.
You can easily combine two files in Python.
To concatenate two files, you can read the content from both files, store the contents in strings, concatenate the strings and then write the final string to a new file.
Below is a simple example showing you how to merge two files into one using Python.
with open('file1.txt') as f:
f1 = f.read()
with open('file2.txt') as f:
f2 = f.read()
f3 = f1 + "n" + f2
with open('file3.txt','w') as f:
f.write(f3)
How to Concatenate Multiple Files in Python
If you have more than two files, or want to create a function for a variable number of files, you can do the following.
First, we can create a list of strings where each element contains the contents of each file. Then, you can join the elements of the strings together with join() and a newline character.
Below is a function which will allow you to append more than two files together in Python.
def concat_files(filenames, outfile):
contents = []
for filename in filenames:
with open(filename) as f:
contents.append(f.read())
with open(outfile,'w') as f:
f.write("n".join(contents))
You can also open the output file and simply write each file’s contents to that file directly.
def concat_files(filenames, outfile):
contents = []
with open(outfile,'w') as out:
for filename in filenames:
with open(filename) as in:
out.write(in.read())
out.write("n")
Hopefully this article has been useful for you to learn how to concatenate multiple files in Python.