I have 2 text files, like ['file1.txt', 'file2.txt']. I want to write a Python script to concatenate these files into a new file, using basic functions like open() to open each file, read line by line by calling f.readline(), and write each line into that new file using f.write(). I am new to file handling programming in python. Can someone help me with this?
The response is already here:
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
What you need (according to comments), is a file with only 2 lines. On the first line, the content of the first file (without break lines) and on the second line, the second file. So, if your files are small (less than ~1MB each, after it can take a lot of memory...)
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
content = infile.read().replace('\n', '')
outfile.write(content)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With