2014-12-07 103 views
0

我可以從CSV文件讀取,但我不確定如何寫入它。Python瓶寫入一個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

這裏有一個方便的解決方案:

>>> 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的示例。

25 /二月/ 2015更新:您還可以看看我的插件:Flask-Excel

1

你可以只添加一行到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')) 

且模板中設置表單動作爲正確的網址

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

我不習慣到燒瓶所以它可能是不正確的

+0

沒有工作,無法識別功能 – 2014-12-07 03:10:36

+0

@LukeGarrigan你有沒有設置一些路由?你能在你的問題中顯示更多代碼嗎?你知道如何處理Flask中的POST請求嗎? – nkobber 2014-12-07 03:19:59

+0

@LukeGarrigan我已經添加了一些代碼來向你展示如何做一些基本的路由。 – nkobber 2014-12-07 03:29:13