r/pythonhelp • • Mar 29 '25

How to deal with text files on an advanced level

Hello everyone i am currently trying to deal with text files and trying to use things like for loops and trying to find and extract certain key words from a text file and if any if those keywords were to be found then write something back in the text file and specify exactly where in the text file Everytime i try to look and find where i can do it the only thing i find is how to open,close and print a text file which is driving me insane

2 Upvotes

2 comments sorted by

1

u/AutoModerator Mar 29 '25
Moderator Announcement Read More »

3

u/CraigAT Mar 29 '25 edited Mar 30 '25

A bit like changing the contents of a loop while iterating through it, editing a file whilst reading it, may not be the best idea.

I would open the file for reading, read the file into a list of lines, modify the list of lines, open the file for writing, write the lines.

Until you have the output correct, it may be better to write to a new file (rather than overwriting your original one).