[Tutor] file open (take 2)
Terry Carroll
carroll at tjc.com
Thu Sep 28 02:55:22 CEST 2006
On Wed, 27 Sep 2006, Dave S wrote:
> I am trying to read in an ascii text file, do some alterations and write it
> back.
>
> file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+')
> lines = file.readlines()
>
> ... process lines ...
>
> file.writelines(lines)
> file.close()
>
> works but ends up appending a second modified copy to the original ... as per
> the python ref.
I'm surprised it wors at all. When I use writelines on a file that's
opened for read, I get an IOError.
>>> f = open("glorp.txt","r")
>>> lines = f.readlines()
>>> lines.reverse() # just something to show the file's been changed
>>> f.writelines(lines)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: (0, 'Error')
> Am I right in thinking that the only way is to open with a 'r', close them
> open with a 'w' ?
Yup:
>>> f = open("glorp.txt","r")
>>> lines = f.readlines()
>>> lines.reverse()
>>> f.close()
>>> f = open("glorp.txt","w")
>>> f.writelines(lines)
>>> f.close()
More information about the Tutor
mailing list