简体   繁体   English

如果没有数据,请勿使用csv DictWriter写入文件

[英]Don't write file with csv DictWriter if there is no data

I have a Python (3.4) routine that writes a csv file using a generator. 我有一个Python(3.4)例程,该例程使用生成器写入一个csv文件。 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. 但是,根据参数集,可能没有任何数据,在这种情况下,我不希望写入csv文件。 (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))

You could use itertools to take a look at the first item and then sort of put it back into the generator: 您可以使用itertools查看第一项,然后将其放回到生成器中:

import itertools
gen = generator(from_date, to_date, client)
try:
    # try to get an element
    first = next(gen)
except StopIteration:
    pass
else:
    # run this if there was no exception:
    gen = itertools.chain([first], gen)
    csv_writer.writeheader()
    csv_writer.writerows(gen)

This is a little shorter, but may be harder to read: 这有点短,但可能更难阅读:

import itertools
gen = generator(from_date, to_date, client)
try:
    # pop an element then chain it back in
    gen = itertools.chain([next(gen)], gen)
except StopIteration:
    pass
else:
    # run this if there was no exception:
    csv_writer.writeheader()
    csv_writer.writerows(gen)

Or this doesn't use visible try / catch code (although there's probably an equal amount down inside next() ): 或这不使用可见的try / catch代码(尽管next()可能有相等的数量):

import itertools
sentinel = object()  # special flag that couldn't come from the generator
gen = generator(from_date, to_date, client)

# try to get something
first = next(gen, sentinel)
if first is not sentinel:
    # got a meaningful item, put it back in the generator
    gen = itertools.chain([first], gen)
    csv_writer.writeheader()
    csv_writer.writerows(gen)

(These were inspired by Stephen Rauch's answer, but with a few tweaks.) (这些灵感来自Stephen Rauch的答案,但有一些调整。)

You can sort of preview the generator using next() , being careful to preserve the first generated value, with something like: 您可以使用next() 预览生成器,注意保留第一个生成的值,例如:

csv_gen = generator(from_date, to_date, client)
try:
    first_item = next(csv_gen)
except StopIteration:
    csv_gen = None

if csv_gen is not None:
     # prep for write csv
     ....         

    # write csv header
    csv_writer.writeheader()

    # write item already read from generator
    csv_writer.writerow(first_item)        

    # write rest of generator
    csv_writer.writerows(csv_gen)

Please note that this was not tested, so may contain silly typos. 请注意,这未经测试,因此可能包含愚蠢的错别字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM