【发布时间】:2018-03-13 08:18:26
【问题描述】:
我刚刚开始使用 python。 我的目标是使用烧瓶构建一个程序,该程序通过文件上传将 csv 文件作为输入,在 csv 上执行代码并返回一个新的 csv。
每当我尝试运行代码时,上传文件时总是出现以下错误:
TypeError: convert() 缺少 1 个必需的位置参数: '文件名'
我的代码如下:
import os
from flask import Flask, render_template, redirect, request, send_from_directory, url_for
from werkzeug.utils import secure_filename
app = Flask(__name__)
ALLOWED_EXTENSIONS = set(["csv"])
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['GET', 'POST'])
def upload_file():
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):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('convert', filename=filename))
@app.route("/convert")
def convert(filename):
with open (UPLOAD_FOLDER + filename, "r", encoding="UTF-8") as file:
umlaute_dict = {
'ä': 'ae', # U+00E4 \xc3\xa4
'ö': 'oe', # U+00F6 \xc3\xb6
'ü': 'ue', # U+00FC \xc3\xbc
'Ä': 'Ae', # U+00C4 \xc3\x84
'Ö': 'Oe', # U+00D6 \xc3\x96
'Ü': 'Ue', # U+00DC \xc3\x9c
'ß': 'ss', # U+00DF \xc3\x9f
'/': '',
}
with open(UPLOAD_FOLDER + 'csvfile.csv', 'w') as filetwo:
for row in file:
final = " "
list = row.split(",")
line = []
firstname = list[5]
for k in umlaute_dict:
firstname = firstname.replace(k, umlaute_dict[k])
title = list[8]
for k in umlaute_dict:
title = title.replace(k, umlaute_dict[k])
line.append(firstname + ",")
line.append(list[7] + ",")
line.append(title + ",")
line.append(list[9] + ",")
final = "".join(line)
print (final)
filetwo.write(final)
filetwo.write('\n')
return redirect(url_for('uploaded_file', filename=filetwo))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
app.run(debug=True)
感谢您的帮助!!
最好的
【问题讨论】:
-
为什么不上传完整的错误(包括行号)?然后我们可以准确地看到错误发生的位置以及导致错误的原因,而不是在代码中寻找对
convert的调用。
标签: python file-upload flask typeerror