How do you write something into a file without deleting the rest? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How do you write something into a file without deleting the rest?

The real question is how to write something in a file at specifically a certain lign, such as 3. If you just use f.writelines(), then that erases the file and replaces it with whatever is written.

31st Oct 2019, 12:40 PM
Nathan Berglas
Nathan Berglas - avatar
5 Answers
+ 6
Let's say: with open(filename) as f: L = f.readlines() L = L[:-1] # To remove the \n at the end, unless it's the last line L[3]+='your text here'+'\n' with open(filename, 'w') as f: f.write(L) This will NOT remove any content in your file, and will append what you want to the desired line.
31st Oct 2019, 3:12 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 6
Change mode, instead of "w" (wrting mode) use "a" (append mode) , the append mode adds text to at the end of what is already in the file I.e with open("file_name.txt, "a") as file: file.write("New text added")
31st Oct 2019, 1:06 PM
Cebo Sithole
Cebo Sithole - avatar
+ 5
Just read it using readlines() and close the file., This will give you a list, each element is a line. Use the list.insert() method to insert what you want in the line you want. Then reopen the file using write mode, and write that list to the file.
31st Oct 2019, 12:45 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 5
Cebo Soul append mode adds content the the end of the file, he wants to add contents in a line of his choice, so it's not an option
31st Oct 2019, 2:40 PM
Aymane Boukrouh
Aymane Boukrouh - avatar
+ 2
I could use the the insert() but it moves everything over, I want to overwrite
31st Oct 2019, 2:49 PM
Nathan Berglas
Nathan Berglas - avatar