我需要一些帮助。我需要使用Python将.csv
文件保存到本地文件夹中,但它存储空白文件。我在下面解释我的代码。
views.py:
report = Reactor.objects.all()
filename = str(uuid.uuid4()) + '.csv'
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename='+filename
with open(settings.FILE_PATH + filename, 'w') as csv_file:
file_writer = csv.writer(csv_file)
response_writer = csv.writer(response)
file_writer.writerow(['Name', 'Status', 'Date'])
response_writer.writerow(['Name', 'Status', 'Date'])
for rec in report:
if rec.status == 1:
status = 'Start'
if rec.status == 0:
status = 'Stop'
if rec.status == 2:
status = 'Suspend'
file_writer.writerow([rec.rname, status, rec.date])
response_writer.writerow([rec.rname, status, rec.date])
return response
settings.py:
FILE_PATH = os.getcwd()+'/upload/'
这里我也在下载文件,我需要将该文件保存到文件夹中,但这里存储了一些空白文件。请帮帮我。
答案 0 :(得分:0)
正如jasonharper所说,你只是将csv数据写入响应,而不是写入磁盘上的文件。首先创建另一个编写器对象:
file_writer = csv.writer(open(settings.FILE_PATH + filename, 'w'))
现在,每当您在writer
上拨打撰写时,也会为file_writer
执行此操作:
file_writer.writerow(['Name', 'Status', 'Date'])
...
file_writer.writerow([rec.rname, status, rec.date])
最好使用with
语句让python自动关闭文件:
with open(settings.FILE_PATH + filename, 'w') as csv_file:
file_writer = csv.writer(csv_file)
response_writer = csv.writer(response)
file_writer.writerow(['Name', 'Status', 'Date'])
response_writer.writerow(['Name', 'Status', 'Date'])
for rec in report:
...
file_writer.writerow([rec.rname, status, rec.date])
response_writer.writerow([rec.rname, status, rec.date])
return response