3

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?

Shraddha
  • 183
  • 1
  • 2
  • 10

2 Answers2

7

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)

Flat line solution

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)
Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • 1
    thanks. It works, but how do i place them in different lines like line1 contents of file1 then in next line contents of line2 and so on.. – Shraddha Dec 01 '13 at 15:53
  • @Pramod You want to alternate line or to flat the content of each file on 1 line to have an output on 2 lines only? – Maxime Lorant Dec 01 '13 at 15:55
  • file1 and file 2 both have one line text. So in the new merged file, line 1 should be file1 then next line file2. – Shraddha Dec 01 '13 at 15:56
2
f1 = open("file1.txt")
f1_contents = f1.read()
f1.close()

f2 = open("file2.txt")
f2_contents = f2.read()
f2.close()

f3 = open("concatenated.txt", "w") # open in `w` mode to write
f3.write(f1_contents + f2_contents) # concatenate the contents
f3.close()

If you're not particular on Python, the UNIX cat command does exactly that: concatenates the contents of multiple files.

If you want a line break between the two files, change the second-to-last line to have f1_contents + "\n" + f2_contents. (\n means new line).

Hardmath123
  • 341
  • 1
  • 9
  • 1
    This method can be good for small file, but it'll consume a lot of memory with larger files... Be careful. I would also use `with` statement instead of old fashion method open then close... – Maxime Lorant Dec 01 '13 at 15:51
  • Thanks but is it possible to read both files at once and then write the contents in seperate lines on to new file like line1 will have contents of file1 and then in next line, it will have contents of line 2 will have contents of file2. – Shraddha Dec 01 '13 at 15:55