I am trying to build an application which takes different CSV files with a different number of columns. For example, my CSV file has around 30 columns whose field names have special characters. So, I would like to update the field names given by the user.I have a CSV file that looks something like this:
ques.1,ques.2
3,5
5,1
I want to update the column names ques.1, ques.2
with the titles given by the user (TV, Radio).
Python:
def upload():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
app.logger.info('File Saved')
filename = secure_filename(file.filename)
savepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
flash(savepath)
file.save(savepath)
save_in(savepath)
return redirect(url_for('upload', filename=filename))
return render_template('pages/placeholder.upload.html')
def save_in(savepath):
app.logger.info(savepath)
csv_rows = []
with open(savepath) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
I have tried to populate the field names in a selection menu. But I am not able to figure out how to make the user:
- Choose the field-name to update from the selection menu.
- Enter the new field name.
- Click on the "update" button to change the field name.
HTML
<div class="container">
<form class="col s12" action="/upload" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12 m6">
<label>Update Fieldnames</label>
<select class="icons">
{% for x in title %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
</select>
<button class="btn" type="submit" value="Update">Submit</button>
</div>
</div>
</form>
</div>