Using "with open(filename, 'ab'):" and calling code only if the file is new?

Joseph L. Casale jcasale at activenetwerx.com
Tue Oct 29 22:55:53 EDT 2013


> Like Victor says, that opens him up to race conditions.

Slim chance, it's no more possible than it happening in the time try/except
takes to recover an alternative procedure.

with open('in_file') as in_file, open('out_file', 'ab') as outfile_file:
    if os.path.getsize('out_file'):
        print('file not empty')
    else:
        #write header
        print('file was empty')

And if that's still not acceptable (you did say new) than open the out_file 'r+' an seek
and read to check for a header.

But if your file is not new and lacks a header, then what?
jlc



More information about the Python-list mailing list