Das letzte Mal, als ich PDF in Text konvertiert habe, werde ich dieses Mal einen CSV-Reader erstellen. Der Code selbst ist ein Datei-Upload, sieht also fast gleich aus.
csvopnener.py
import os
import csv
from flask import Flask, render_template, request, redirect, url_for, send_from_directory, session
from werkzeug.utils import secure_filename
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['csv'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = os.urandom(24)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('csv.html')
@app.route('/show_csv', methods=['GET', 'POST'])
def show_csv():
if request.method == 'POST':
send_data = request.files['send_data']
if send_data and allowed_file(send_data.filename):
filename = secure_filename(send_data.filename)
send_data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
f = open('uploads/' + filename, 'r')
f_reader = csv.reader(f)
result = list(f_reader)
return render_template('csv.html', result=result)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
app.debug = True
app.run()
csv.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="{{ url_for('show_csv') }}" enctype="multipart/form-data">
<input type="file" id="send_data" name="send_data">
<input type="submit" value="Senden">
</form>
<div>
{% if result %}
<dl>
{% for i in result %}
<dt>{{ i[0] }}<dt>
<dd>{{ i[1] }}</dd>
{% endfor %}
</dl>
{% endif %}
</div>
{% endblock %}
Ich habe eine CSV-Datei für einen solchen Test vorbereitet.
Ich fand es schön, eine Zeile zu CSV hinzuzufügen, wenn ich sie anpassen würde.
Recommended Posts