+ 2

Python: Write to file without Overwriting

In Python, how to write to a file without getting its old contents deleted(overwriting)?

23rd Nov 2017, 4:29 PM
Qazi Omair Ahmed
Qazi Omair Ahmed - avatar
3 Answers
+ 2
Got the answer to this. Instead of opening the file in write mode we have to open it in append ("a") mode. with open("text.txt","a") as file: file.write("new text") print(file.read() The above code will add (new text) to the file (text.txt) at the end of the file without deleting its contents and print the contents of the files. For example, let's assume that earlier the file contained (old text). The output of the code will be: old text new text Correct me if I am wrong! :) Thanks, Omair Ahmed, Currently learning Python at: SoloLearn
23rd Nov 2017, 4:29 PM
Qazi Omair Ahmed
Qazi Omair Ahmed - avatar
+ 1
"without" overwriting
23rd Nov 2017, 4:30 PM
Qazi Omair Ahmed
Qazi Omair Ahmed - avatar
0
"with" or "without" ?
23rd Nov 2017, 4:23 PM
Š’Š°Š“ŠøŠ¼ Š”ухŠ¾Ń‚ŠøŠ½ (Vadim Sukhotin)
Š’Š°Š“ŠøŠ¼ Š”ухŠ¾Ń‚ŠøŠ½ (Vadim Sukhotin) - avatar