[Tutor] Re: file in use oddness with Python 2.3.4 and IDLE 1.0.3 on WinMe

Brian van den Broek bvande at po-box.mcgill.ca
Fri Nov 19 17:08:15 CET 2004


Roel Schroeven said unto the world upon 2004-11-19 05:23:
> Brian van den Broek wrote:
> 
>>
>> def writer(full_file_path, contents):
<SNIP>
>>     result_file = open(full_file_path, 'w')
>>     result_file.writelines(contents)
>>     result_file.close()
> 
> 
>> The program I'm currently working on uses the writer() function to 
>> write a simple log file if a call to os.rename() raises an OSError 
>> Exception
>> (which is expected and caused by the destination filepath of the
>> os.rename call already existing). Before using writer(), it checks if 
>> the file exists, and, if it does, uses reader() so as to preserve its 
>> contents.
> 
> 
> I don't know what the problem is, but there's something else: if you use 
> 'a' for the mode in the open() call, new output to the file will be 
> appended to the end; the old content will not be overwritten or truncated:
> 
>     result_file = open(full_file_path, 'a')
> 
> That way you don't have to read and rewrite the old contents in order to 
> preserve them.
> 

Hi Roel,

thanks for the tip. I did know about that; I've been meaning to 
'upgrade' my writer() function to use a keyword argument with a default 
value to incorporate it. But, the files I process are almost all well 
under 1MB, and the tutor list helped cure me of my case of the newbie's 
"I need the *most* efficient way! Right *now*!" disease ;-) So, I've 
just not bothered.

Thanks again,

Brian vdB



More information about the Tutor mailing list