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

Zachary Ware zachary.ware+pylist at gmail.com
Tue Oct 29 23:28:41 EDT 2013


On Tue, Oct 29, 2013 at 8:02 PM, Victor Hooi <victorhooi at gmail.com> wrote:
> Hi,
>
> I have a CSV file that I will repeatedly appending to.
>
> I'm using the following to open the file:
>
>     with open(self.full_path, 'r') as input, open(self.output_csv, 'ab') as output:
>         fieldnames = (...)
>         csv_writer = DictWriter(output, filednames)
>         # Call csv_writer.writeheader() if file is new.
>         csv_writer.writerows(my_dict)
>
> I'm wondering what's the best way of calling writeheader() only if the file is new?
>
> My understanding is that I don't want to use os.path.exist(), since that opens me up to race conditions.
>
> I'm guessing I can't use try-except with IOError, since the open(..., 'ab') will work whether the file exists or not.
>
> Is there another way I can execute code only if the file is new?
>
> Cheers,
> Victor

I've not tested, but you might try

with ... open(...) as output:
    ...
    if output.tell() == 0:
        csv_writer.writeheader()
...

HTH

--
Zach

(failed to send to the list first time around...)



More information about the Python-list mailing list