how to write a line in a text file

Steven D'Aprano steve at REMOVEMEcyber.com.au
Tue Jul 26 10:00:17 CEST 2005


en.karpachov at ospaz.ru wrote:
> Tue, Jul 26, 2005 at 01:41:36PM +1000, Steven D'Aprano пишет:
> 
>>Long ago, when dinosaurs roamed the Earth, (a.k.a. 
>>"before OS X on the Macintosh") Apple suggested a bit 
>>of Pascal code for safely updating a file:
>>
>>http://developer.apple.com/documentation/mac/Files/Files-25.html#MARKER-9-163
> 
> 
> That snippet doesn't write data to the existing file. It writes data into
> the new tempfile and then renames it, as well as the FileInput object does.

Obviously you can't *directly* overwrite a file and 
expect good things to happen if the disk crashes 
half-way through. Any sort of safe overwrite must use 
an intermediate file somewhere. That goes without saying.

As for the FileInput object doing the job "as well as" 
the old Mac file system, no it does not. I've already 
described how the FileInput object is only usable in a 
vanishingly small subset of all potential file 
overwrites, namely when you are writing stdout to the 
same text file you read from -- or at least one of the 
multiple files you read from.

If that solution works for your needs, you should use 
it. But if you are not writing to stdout, your data 
isn't text, and you didn't get it from the same file 
you are overwriting, the FileInput solution is no 
solution at all.

>>Most of the code is Macintosh-specific, but the 
>>principle is not: when over-writing a file, make sure 
>>that the user can recover from any error up to and 
>>including power failure without losing the data on disk.
> 
> 
> Well, it's what (R)DBMS are for, but plain files are not.

This isn't 1970, users expect more from professional 
programs than "keep your fingers crossed that nothing 
bad will happen". That's why applications have multiple 
levels of undo (and some of them even save the undo 
history in the file) and change-tracking, and auto-save 
and auto-backup. Even in the less-than-user-friendly 
world of Linux many applications implement their own 
version of data protection.

Now maybe you feel that it is overkill for your program 
to bother about the tiny chance of data loss when 
saving data. That's fine. For 99% of my scripts, I 
don't even bother with try...except blocks when writing 
to a file. I just open it and write to it and hope it 
all works.

But for that other 1%, I take the time to check for 
errors and allow the program to recover gracefully. And 
that means, if you are about to save the user's work, 
you better be sure that if the save fails for any 
reason, you haven't blown away their precious data. If 
you want to live dangerously with your own data, go for 
it. But destroying the user's data is the biggest 
programming sin of all.


-- 
Steven.




More information about the Python-list mailing list