I have a Python (3.4) routine that writes a csv
file using a generator. However, depending on the parameter set, there may not be any data, in which case, I don't want the csv
file to be written. (It would just write the file with a header only).
Right now, the bandaid is to count the lines after generation and then delete the file, but surely there must be a better way, while retaining the pattern of having a generator being the only code that's aware of whether there is data for the given parameters, (nor having to call on the generator twice):
def write_csv(csv_filename, fieldnames, generator, from_date, to_date, client=None):
with open(csv_filename, 'w', newline='') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames, delimiter='\t')
csv_writer.writeheader()
csv_writer.writerows(generator(from_date, to_date, client))
# If no rows were written delete the file, we don't want it
with open(csv_filename) as f:
lines = sum(1 for _ in f)
if lines == 1:
f.close()
os.remove(f.name)
def per_client_items_generator(from_date, to_date, client):
return (per_client_detail(client, sales_item) for sales_item in
sales_by_client.get(client))