[Tutor] File access codes in Python

alan.gauld@bt.com alan.gauld@bt.com
Sun, 19 May 2002 18:19:38 +0100


>  In Tcl, one can open a file for reading, writing, 
> and both reading AND writing. 

> However, in Python, it appears from the book I have, and 
> from some online information, that one does not have the 
> option to open a file for BOTH reading and writing.


You do, but its unusual and risky.

> it complicates the situation. 

Actually having a file do both is the com,plicated bit, 
even in Tcl. Its very easy to wind up overwriting a bit 
of data you didn't mean to and you have to constantly 
track your location in the file. Very messy and to be 
avoided if posdsible IMHO.

> a program TWICE, just to read the file at one point, 
> and then write to the same file at some other point 

Its how most programs work(eg MS Word, Excel etc)
Its much safer since you work on a backup copy of the 
data and can revert in the case of an error.

But if you must do it, check out the "r+" option of open()

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld