Python烧瓶写入csv文件并阅读它

时间:2014-12-07 02:22:19

标签: python html forms csv flask

我可以从CSV文件中读取,但我不确定如何写入它。

我们的想法是允许用户输入他们的评论并将其保存在CSV文件中,然后再打印出评论

这是阅读csv文件的阅读代码

from flask import Flask, render_template
from flask import request
import csv

def comments():
    with open('static\\comments.csv', 'r') as inFile: 
        reader = csv.reader(inFile)
        commentsList = [row for row in reader]

以下是我用来显示csv文件中的字段的代码。我想使用表单以某种方式将字段添加到给定的csv文件

<table border="1">
    {% for line in commentsList %}
    <tr>
    {% for item in line%}
    <td>
    {{item}}
    </td>
    {% endfor %}
    </tr>
    {% endfor %}
    </table>
    </div>
    <form action="addToComments" method="post">
    Name: <input type="text" name="username">
    Comment: <input type="text" name="comment">
    Date: <input type="date" name="date">
    <input type="submit" value="Submit">
    </form> 

2 个答案:

答案 0 :(得分:3)

这是一个方便的解决方案:

>>> import pyexcel as pe
>>> a=[["someone", "good one", "01/Dec/14"]]
>>> sheet = pe.Sheet(a)
>>> sheet
Sheet Name: pyexcel
+---------+----------+-----------+
| someone | good one | 01/Dec/14 |
+---------+----------+-----------+
>>> sheet.colnames=["username", "comment", "date"]
>>> sheet
Sheet Name: pyexcel
+----------+----------+-----------+
| username | comment  |   date    |
+==========+==========+===========+
| someone  | good one | 01/Dec/14 |
+----------+----------+-----------+
>>> sheet.save_as("comments.csv")
>>> exit()

$ cat comments.csv
username,comment,date
someone,good one,01/Dec/14

如果您需要从文件中读取csv文件:

>>> import pyexcel as pe
>>> sheet = pe.load("comments.csv", name_columns_by_row=0)
>>> sheet
Sheet Name: csv
+----------+----------+-----------+
| username | comment  |   date    |
+==========+==========+===========+
| someone  | good one | 01/Dec/14 |
+----------+----------+-----------+

这是how to handle upload and download using Flask and pyexcel上的一个例子。

2015年2月25日的更新:您还可以查看我的插件:Flask-Excel

答案 1 :(得分:2)

您只需在csv文件中添加一行即可。

只需从POST请求中获取字段并将其附加到文件中。

s = ",".join([username, comment, date])

fd = open("path/to/file.csv", "a")
fd.write(s)
fd.close()

a模式打开文件会将流定位在文件的末尾。

更新:为您创建了一个示例。

from flask import url_for

@app.route("/add-comment/", methods=["POST"])
def add_comment():
    username = request.form["username"]
    comment = request.form["comment"]
    date = request.form["date"]

    f = open('static\\comments.csv', 'a')
    f.write(",".join([username, comment, date])
    f.close()

    return redirect(url_for('comments'))

在您的模板中,将表单操作设置为正确的URL

<form action="/add-comment/" method="post">

我不习惯烧瓶所以它可能不正确