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

Antoon Pardon antoon.pardon at rece.vub.ac.be
Wed Oct 30 03:53:41 EDT 2013


Op 30-10-13 02:02, Victor Hooi schreef:
> 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?

If you are using 3.3 you could use something like this:

with open(self.full_path, 'r') as input:
    try:
        output = open(self.output_csv, 'abx')
        new_file = True
    except FileExistsError:
	output = open(self.output_csv, 'ab')
        new_file = False
    fieldnames = (...)
    csv_writer = DictWriter(output, filednames)
    if new_file:
        csv_writer.writeheader()
    csv_writer.writerows(my_dict)



More information about the Python-list mailing list