Save-to-file code not quite working completely
dn
PythonList at DancesWithMice.info
Sat Aug 8 19:50:51 EDT 2020
On 09/08/2020 08:51, Steve wrote:
>
> I have a file containing specifications. My .py program can read and
> manipulate the data but I cannot seem to get it to update the original file
> properly.
>
> The code is simple and works except that the original line remains in the
> file after the new updated one has been added.
...
> That second line shown was the original line for MSN. The replacement line
> should have replaced the original line not just get added to the file. It
> should have been replaced. What is in line 2, should have "1 MSN" at the
> beginning but that somehow disappeared.
>
> So close, so simple...
> How do I fix this?
To be a logomach, let's talk about "update":-
May I advise that a 'good practice' would be to create a new file, and
thus be able to (also) maintain the old version as a 'backup'.
(also: advantage when debugging/testing logic!)
The pattern is to read the 'old' file, line-by-line. If there is a
key-match, ignore the read record, writing the new data in its stead.
If there is not a match, copy the input-data into an output record.
The major addition will be the need to rename the 'old file', ensuring
logic to handle any "clash" (based upon whatever security
requirements/numbers of generations - which it would appear don't
currently exist).
The above assumes that the program will either only ever update a single
record per execution-run; or that the logic collects a list of changes
to the file which will be saved to the file, as above.
Further, databases have been designed for this sort of partial update
scenario. If/when updates become too frequent, or the file becomes
extensive, recommend you look at using an RDBMS instead of using this
'flat-file' approach...
--
Regards =dn
More information about the Python-list
mailing list