使用flask上传多个文件,并将其作为变量读取



我有一个python脚本,读取2个文件的内容,并映射数据并输出csv。目前,代码读取文件的路径,但我想要它,以便用户上传文件,代码读取文件并生成csv.

我启动了上传多个文件的flask代码,但我需要帮助将文件保存为python脚本能够读取的变量。

我的python脚本:
user_input = input("Enter the path of First File : ")
user_input2 = input("Enter the path of Second File : ")
assert os.path.exists(user_input), "Invalid file at, " + str(user_input)
f = open(user_input, 'r')
f2 = open(user_input2, 'r')
content = f.read()
content2 = f2.read()
def parse_value(txt):
reclines = []
for line in txt.split('n'):
if ':' not in line:
if reclines:
yield reclines
reclines = []
else:
reclines.append(line)
def parse_fields(reclines):
res = {}
for line in reclines:
key, val = line.strip().rstrip(',').split(':', 1)
res[key.strip()] = val.strip()
return res
res = []
for rec in parse_value(content):
res.append(parse_fields(rec))    
res2 = []
for rec in parse_value(content2):
res2.append(parse_fields(rec))    
df = pd.json_normalize(res)
df2 = pd.json_normalize(res2)

flask代码用于上传文件:

upload.py
import os
import magic
from app import app
from flask import Flask, flash, request, redirect, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['tpi'])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return render_template('button.html')
@app.route('/', methods=['POST'])
def upload_file():
if request.method == 'POST':
print(request.__dict__)
# check if the post request has the file part
if 'sfile' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['sfile']
if file.filename == '':
flash('No file selected for uploading')
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))
flash('File successfully uploaded')
return redirect('/')
else:
flash('Allowed file types are tpi')
return redirect(request.url)
if __name__ == "__main__":
app.run(host="0.0.0.0", port = 5000, debug=True)

button.html

<!doctype html>
<title>Python Flask File Upload Example</title>
<h2>Upload First File</h2>
<form method="post" name="sform" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="sfile" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" name="ssubmit" value="Submit">
</p>
</form>
<h2>Upload Second File</h2>
<form method="post" name="wform" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="file" name="sfile" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" name="wsubmit" value="Submit">
</p>
</form>

我如何修复烧瓶代码保存第一次上传的文件到变量f和第二次上传的变量f2?

您正在寻找的是.read()方法。

with open(user_input, 'r') as file:
file_one = file.read()
with open(user_input, 'r') as file:
file_two = file.read()

您可能需要在上下文管理器之外实例化文件变量,但是像这样的东西应该可以让您开始

最新更新