0

i would like to add the content of one file at the end of the content of the other file. i have let say:

The content of the file1 is :  james@29@458462


The content of the file2 is : marc@45@4695588

after appending file2 into file1 i would like to have:

 james@29@458462
 marc@45@4695588

This is the code i tried to use but it replace the content of the target file with the source file:

file1=open("test1.txt","a")
file2=open("test2.txt","r")
file1.write(file2.read())

Can i please have a way of appending at the end of one file without replacing the content of the target file?

Thank you

user3841581
  • 2,637
  • 11
  • 47
  • 72

2 Answers2

1

Try using with when you are working with files (https://docs.python.org/2/reference/compound_stmts.html#the-with-statement) :

with open("test1.txt","a") as file1, open("test2.txt","r") as file2:
    for line in file2:
        file1.write('\n' + line)
Andy M
  • 596
  • 3
  • 7
0

You can use bash script commands in python to append two files together as following:

import subprocess as S

CMD="cat file1.txt file2.txt > new.txt"
S.call([CMD],shell=True)
Dalek
  • 4,168
  • 11
  • 48
  • 100
  • A lot of overhead to run bash from python for such a simple operation. – dfranca Aug 14 '14 at 16:25
  • @danielfranca I don't think there is any overhead using bash commands. It does much better job dealing with txt files than python. – Dalek Aug 14 '14 at 16:27
  • I did a test, putting in a small loop (1000 iterations), both a normal python implementation and a bash implementation, as you can see here: http://pastebin.com/4zp7r1qs And the python one was much faster: http://pastebin.com/pa1ytN7c – dfranca Aug 14 '14 at 16:39
  • @danielfranca well I didn't measure the time but from my experience using bash script to concatenate files rows and columns is much faster than python. However, I haven't seen any where in this post is mentioned that the speed of the performance is vital for the author! – Dalek Aug 14 '14 at 16:49