Basically if we have a temp1.txt with text 'qwertyuiop' and a temp2.txt with text 'asdfghjkl' how can I copy the text of temp1.txt onto temp2.txt without deleting the text it has. I found that I can use the os and shutil modules (https://stackabuse.com/how-to-copy-a-file-in-python/) but they delete the existing text and replace it with the new one. Any and all help is greatly appreciated
Asked
Active
Viewed 34 times
2 Answers
1
You open the first file with append to end ('a+'
) and add the second files content:
with open("temp1.txt","w") as f:
f.write('qwertyuiop')
with open("temp2.txt","w") as f:
f.write('asdfghjkl')
# open f1 with append, open f2 as read, append text:
with open ("temp1.txt","a+") as f1, open("temp2.txt") as f2:
f1.write(f2.read())
print(open("temp1.txt").read())
Output:
qwertyuiopasdfghjkl

Patrick Artner
- 50,409
- 9
- 43
- 69
0
You can try opening temp2.txt file in append mode:
temp2 = open(temp2.txt, 'a'):
This way you can append text to the file

PMM
- 366
- 1
- 10