[Tutor] file open (take 2)

Luke Paireepinart rabidpoobear at gmail.com
Thu Sep 28 03:24:20 CEST 2006


>> I am trying to read in an ascii text file, do some alterations and write it 
>> back.
>>     
Sounds like a pretty useful thing to do :)
>> file = open(self.config.get('pdf','cert') + '/cert.pdf' , 'r+')
>> lines = file.readlines()
>>     
Not sure what self.config.get here is doing, but that's not exactly 
pertinent to the discussion.
>> ... 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.
>   
Notice the "r+" mode that Dave is using.
>   
>>>> 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')
>   
Here Terry's using "r".

"r+" means open for reading and appending.
"r" is just normal reading.
>   
>> Am I right in thinking that the only way is to open with a 'r', close then 
>> open with a 'w' ?
>>     

I believe Dave could somehow remove the contents of the file,
and put back in what he wants, but it's probably easier to just reopen 
the file.


More information about the Tutor mailing list