Small Legend
Small Legend

Reputation: 688

Python flask writing to a csv file and reading it

I can read from the CSV file but I'm unsure as to how I can write to it.

The idea is to have allow the user to enter their comment and it save on the CSV file and then further print out the comment

This is the code for reading for reading the csv file

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]

Here is the code that I am using to display the fields within the csv file. I want to use the form to somehow add fields to the given csv file

<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> 

Upvotes: 0

Views: 8602

Answers (1)

chfw
chfw

Reputation: 4592

Here's a handy solution:

>>> 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

If you will need to read the csv file from file:

>>> 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 |
+----------+----------+-----------+

And here's an example on how to handle upload and download using Flask and pyexcel.

An update on 25/Feb/2015: you may also have a look at my plugin: Flask-Excel

Upvotes: 3

Related Questions