File modes

Daniel Nogradi nogradi at gmail.com
Thu May 10 17:27:01 EDT 2007


> After reading a file is it possible to write to it without first
> closing it? I tried opening with 'rw' access and re-winding. This does
> not seem to work unless comments are removed.
>
>
> Also, does close force a flush?
>
> Thanks,
>
> jh
>
> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> f = open('c:\\tempMaxq\\incidents.txt', 'rw')
> s = f.read()
> lst = s.split()
> incId = []
> incId.extend([lst.pop(), lst.pop()])
> #f.close()
> #f = open('c:\\tempMaxq\\incidents.txt', 'w')
> #f.seek(0)
> for el in lst:
>     f.write(el + ' ')
> f.close()


Please see the documentation of the function open( ):
http://python.org/doc/lib/built-in-funcs.html It says that the modes
can only be 'r', 'w', 'a', 'r+', 'w+', 'a+' and possibly a 'b' or 'U'
appended to these. So if you open it with 'rw' it will be interpreted
as 'r'. For example this will not work:

f = open( 'myfile', 'rw' )
f.write( 'hello' )
f.close( )

because python thinks you want to open 'myfile' in 'r' mode. I guess I
agree that the thrown exception IOError: [Errno 9] Bad file descriptor
is not very informative in this case.

HTH,
Daniel



More information about the Python-list mailing list