如何使用Python

时间:2017-08-29 07:09:18

标签: python django

我需要一个帮助。我正在将文件上传到文件夹中,为此我使用Python在settings.py文件中设置了常量。我在下面解释我的代码。

  

settings.py:

FILE_PATH = os.getcwd()+'/upload/'
  

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

在这里,我需要安全的文件路径,使用Python和Django将下载的文件上传到文件夹中。

1 个答案:

答案 0 :(得分:0)

您是否逐行写入文件?我会首先制作一个列表或数据框。然后把它写到csv。

import pandas as pd

#make your dataframe by adding your rows to a list
df = pd.DataFrame(list)   
df.to_csv(filepath)