如何在csv文件中编写数据库内容并使用Python

时间:2017-09-09 09:57:22

标签: python csv urllib

我需要一些帮助。我需要写入csv file并使用Python下载它。我在下面解释我的代码。

<form method="get" action="{% url 'createfile' %}">
{% csrf_token %}
<label>Type File Name: </label>
<textarea rows="4" cols="100" name="file">
</textarea>
<br>
<button type="submit">Download</button>
</form>
  

views.py:

def createfile(request):
    """ In this function remote file path is included """

    if request.GET.get('file') is not None and request.GET.get('file') != '':
        file = request.GET.get('file')
        response = urllib.urlopen(file)
        lines = response.readlines()
        report = Reactor.objects.all()
        return HttpResponse(content=lines, content_type="text/html")
    else:
        return render(request, 'plant/home.html', {'count': 1})

反应器:

id      name        status

 1      Reactor1      1

 2      Reactor2      0

此处用户提供文件名,并使用此文件将avobe数据库内容写入csv文件。最后这个文件将被下载。

1 个答案:

答案 0 :(得分:0)

试试这个:

import csv

txt = """id      name        status

1      Reactor1      1

2      Reactor2      0
"""

def write_to_csv(file_name, input_str):
    with open(file_name, 'w', encoding="utf-8") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=["id", "name", "status"], delimiter=';')
        writer.writeheader()

        writer = csv.writer(csvfile)
        for line in input_str.splitlines():
            lines = line.split()
            if len(lines) != 3:
                continue
            _id, name, status = lines
            if _id == "id":
                continue

            writer.writerow([_id, name, status])

if __name__ == "__main__":
    write_to_csv('csv_test.csv', txt)