Writing files in python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Writing files in python

when I am using file.write(), y=the contents are getting deleted, can we get that it doesn't delete the original contents but writes after the original contents.

7th Dec 2019, 12:59 PM
Yash
Yash - avatar
4 Answers
+ 5
You would need to open the file in append mode.
7th Dec 2019, 1:06 PM
Seb TheS
Seb TheS - avatar
+ 4
with open(filename, "a") as f: f.write(content)
7th Dec 2019, 1:06 PM
Seb TheS
Seb TheS - avatar
+ 4
I found this in the comments of the lesson: To edit an existing file without losing previous data use append(a) instead of write(w) for example : file = open("newfile.txt", "a") file.write("\nThis has been written again to a file") file.close()
7th Dec 2019, 1:08 PM
Coding Cat
Coding Cat - avatar
+ 2
8th Dec 2019, 1:39 AM
Yash
Yash - avatar