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

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Fri Nov 19 11:23:20 CET 2004


Brian van den Broek wrote:
> 
> def writer(full_file_path, contents):
>     '''writes contents to file and closes it when done.
> 
>     Given a full file path (or a file name in which case the current
>     working directory is assumed) and a list of file contents, writer()
>     writelines the contents to the file and closes it.
>     '''
>     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.

-- 
"Codito ergo sum"
Roel Schroeven



More information about the Tutor mailing list