+ 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.
5 odpowiedzi
+ 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.
+ 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")
+ 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.
+ 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
+ 2
I could use the the insert() but it moves everything over, I want to overwrite