0

I have a script that pulls data and writes it into a TXT file, then in the same code I have a For Loop that changes the format by replacing quotes to double quotes and concatenates the result with a text in another new file.

with open ('myfile.txt', 'w') as f:
    print(response['animals']['mammals'], file=f)
fout = open("mynewfile.txt", "wt")      
f = open('myfile.txt', 'r')  
for line in f:
    x = str(line).replace("'", '"')  
    fout.write(f"mammals = {x}")        
f.close()          
fout.close()    

The result is basically that all that is in myfile.txt with quotes i.e ['dog', 'cat'] it is edited and written in mynewfile.txt as mammals = ["dog", "cat"], that is cool. But I also want to manually add some other text to mynewfile.txt and every time I need to update that data and run the script, the data that I enter manually is deleted because of the For Loop.

Is there a way to overwrite just that line without touching the rest of the lines in the file?

Kikeman26
  • 49
  • 1
  • 10
  • 1
    Have you considered opening the file in "append" mode? ``` fout = open("mynewfile.txt", "a") ````. This will prevent the file from being overwritten and will add new lines to the end. – Shashank Holla Nov 15 '22 at 18:22
  • Thanks for the reply @Shashank Holla, Let me edit my question, but basically I want exactly that, I want my specific line overwritten and just that line, not the rest of the lines in the file. – Kikeman26 Nov 15 '22 at 18:31
  • You cannot modify a line of text in a file in-place. You need to read the entire file, modify the line, and write all the lines to file. – Michael Ruth Nov 15 '22 at 21:38
  • Does this answer your question? [Editing specific line in text file in Python](https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python) – Michael Ruth Nov 15 '22 at 21:39

1 Answers1

0

Get numbers of strings in list and start indexing from [last_word +1

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 18 '22 at 05:20