[Tutor] file opening modes

Jeff Shannon jeff at ccvcorp.com
Wed Sep 10 12:13:48 EDT 2003


Jimmy verma wrote:
> If i use open(filename,'w')
> or write mode for opening file then as according to the expected 
> behaviour of write mode it erases the contents before writing in the file.
> So i decided to use open(filename, 'a')
> i.e. append mode so that i can append information to the file while i am 
> running the program.
 >
 > [...]
> 
> 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.

I think that the easiest way to do this is to continue to use append 
mode, but to try to delete the files when the program starts up.  Of 
course, you'll have to deal with the case of when the files *don't* 
exist -- trying to os.remove() a nonexistent file gives an error.

There's two ways to do this.  One is to check whether the file exists, 
and if it does, remove it --

if os.path.exists(fname):
     os.remove(fname)

The other is to try to remove it, but catch (and ignore) any errors --

try:
     os.remove(fname)
except OSError:
     pass

Which method you choose is largely a matter of taste.  Some feel 
"safer" if they check first ("look before you leap"); but the second 
method is slightly more efficient (as it only needs to hit the hard 
drive once, rather than twice) and fits the Zen of Python ("it's 
easier to ask forgiveness than permission").

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list