[英]Python CSV function outputs blank CSV when not enough rows?
我有一個函數,該函數接受自定義對象的列表,符合一些值,然后將它們寫入CSV文件。 當列表僅包含幾個對象時,發生的事情確實很奇怪,生成的CSV文件始終為空白。 當列表較長時,該功能可以正常工作。 臨時文件是否有些奇怪?
我必須指出,此函數將臨時文件返回到Web服務器,允許用戶下載CSV。 Web服務器功能位於主要功能下方。
def makeCSV(things):
from tempfile import NamedTemporaryFile
# make the csv headers from an object
headers = [h for h in dir(things[0]) if not h.startswith('_')]
# this just pretties up the object and returns it as a dict
def cleanVals(item):
new_item = {}
for h in headers:
try:
new_item[h] = getattr(item, h)
except:
new_item[h] = ''
if isinstance(new_item[h], list):
if new_item[h]:
new_item[h] = [z.__str__() for z in new_item[h]]
new_item[h] = ', '.join(new_item[h])
else:
new_item[h] = ''
new_item[h] = new_item[h].__str__()
return new_item
things = map(cleanVals, things)
f = NamedTemporaryFile(delete=True)
dw = csv.DictWriter(f,sorted(headers),restval='',extrasaction='ignore')
dw.writer.writerow(dw.fieldnames)
for t in things:
try:
dw.writerow(t)
# I can always see the dicts here...
print t
except Exception as e:
# and there are no exceptions
print e
return f
Web服務器功能:
f = makeCSV(search_results)
response = FileResponse(f.name)
response.headers['Content-Disposition'] = (
"attachment; filename=export_%s.csv" % collection)
return response
任何幫助或建議,不勝感激!
總結eumiro的答案:該文件需要刷新。 在makeCSV()的末尾調用f.flush()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.