简体   繁体   English

如何从html中的python csv读取文件?

[英]How to read file from python csv in html?

I have a problem that I want to read files from CSV and make a loop in it instead of writing one by one in an html page.我有一个问题,我想从 CSV 读取文件并在其中进行循环,而不是在 html 页面中一个一个地写入。 How to read and fetch files from csv in HTML using python code in Django.如何在 Django 中使用 python 代码从 HTML 中的 csv 读取和获取文件。 This code is of index.html .这段代码是index.html

<body>
<center><h1>Article Writing Sites</h1></center>
<div class="row">
   <div class="column">
      {% with open('file.csv') as open%}
   </div>
   <div class="column">
      <p>this is next paragraph</p>
   </div>
</div>
</body>

Lets say you have a view which renders the html given in question.假设您有一个视图可以呈现有问题的 html。 Then you can update the view to open the csv file and read the file.然后您可以更新视图以打开 csv 文件并读取该文件。 Then send the contents of the csv to html:然后将csv的内容发送到html:

import csv
from django.shortcuts import render

def some_view(request):
    reader = csv.DictReader(open('filename.csv', 'r'))
    csv_output = []
    for dict_item in reader:
        csv_output.append(dict_item)
    return render(request, 'template.html', context={'csv_content':csv_output})

Then in template, you need receive that context and iterate through it to show the values in template:然后在模板中,您需要接收该上下文并遍历它以显示模板中的值:

{% for content in csv_content %}
    <div class="row">
       {% for k, v in content.items %}
       <div class="column">
           value for {{k }} is {{ v }}
       </div>
       {% endfor %}
    </div>
{% endfor %}

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

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