[Tutor] file opening modes
Alan Gauld
alan.gauld at blueyonder.co.uk
Thu Sep 11 00:22:12 EDT 2003
> i.e. append mode so that i can append information to the file while
i am
> running the program.
Yes thats the right approach.
> and three files are generated
>
> a.txt, b.txt, c.txt
>
>
> Now suppose if i run the program again then i get into problem
because now
> again these three files will be appending the information in the
existing
> files which i created last time i run the program.
OK so you need to add a tst for file existence before opening it.
Then if it already exists (and the datestamp is within T seconds
of the current time) then use append othewise use 'w' which will
overwrite the old version.
Alternatively do some housekeeping first and copy the old file to
a .bak before creating the new one.
Put the test in a function:
def alreadyExists(fname):
# test here
then your code looks like:
if alreadyExists(fname): mode = 'a'
else: mode = 'w'
f = open(fname,mode)
HTH,
Alan g
More information about the Tutor
mailing list