how to write a line in a text file

Steven D'Aprano steve at REMOVEMEcyber.com.au
Mon Jul 25 23:41:36 EDT 2005


Wade wrote:

> Steven D'Aprano wrote:
> 
>>I'm usually opposed to creeping featuritis in programming languages ("it
>>would be really cool if Python had a built-in command to do my entire
>>application") but safe over-writing of files does cry out for a "batteries
>>included" approach:
> 
> 
> 
> How about the fileinput module?
> 
> http://docs.python.org/lib/module-fileinput.html

Close, but not quite: the "inplace" argument is more 
specific and less general than what I was talking about.

The fileinput solution only works for the specific idiom:

read file A in text mode
process text
write standard output back to file A

compared to the more general idiom:

get data from somewhere
process data
write data to existing file A

In the more general idiom, you don't care whether your 
data is text or binary data, whether you got it from a 
file, whether it was the same file you are writing to, 
or anything else. All you care about is that the file 
you write to happens to already exist.

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

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.

(Presumably if the sun explodes and destroys the Earth, 
your program is allowed to lose data.)


-- 
Steven.




More information about the Python-list mailing list