Hard disk space can not be modified. The data in hard disk is updated with new content.
Content control can be modified.
The file corresponds to the hard disk space, and the hard disk can not be modified.
We can see how the content of the document can be modified.
Train of thought: read the contents of the file in the hard disk into memory, then rewrite it in memory, then cover the hard disk again.
There are two specific ways of realization:
1、Read all the contents of the file into memory at one time, then overwrite and write back to the original file after modifying it in memory
Advantages: only one copy of the same data in the process of document modification.
Disadvantages: too much memory is needed.
2、Open the original file by reading, open a temporary file by writing, read the contents of the original file line by line, write to the temporary file after modifying, delete the original file, rename the temporary file
Advantages: it won’t take up too much memory.
Disadvantages: in the process of document modification, two copies of the same data were saved.
with open('db.txt',mode='rt',encoding='utf-8') as read_f,\
open('.db.txt.swap',mode='wt',encoding='utf-8') as wrife_f:
for line in read_f: