It's not easy to do without rewriting the entire file. Text files are simple, sequential method of data storage, without fixed structure, indexing, or random access search. So you'd have to implement all those features.
The common approach is to read the file, edit it, and overwrite the file with the data the way you want.
Another approach when the file is too big to fit entirely in memory is to create a new temporary file, and read the old file line by line in a loop, while you write to the new file. Then delete the old file and rename the new file to have the same name as the original.
If you need more than that, I suggest using a database. sqlite is included in python and can do what you request directly inside a file, really fast.