我有以下代码使用 Python FLASK 上传 CSV 文件。
from flask_restful import Resource
import pandas as pd
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
class UploadCSV(Resource):
def post(self):
files = request.files['file']
files.save(os.path.join(ROOT_PATH,files.filename))
data = pd.read_csv(os.path.join(ROOT_PATH,files.filename))
print(data)
api.add_resource(UploadCSV, '/v1/upload')
if __name__ == '__main__':
app.run(host='localhost', debug=True, port=5000)
Run Code Online (Sandbox Code Playgroud)
这段代码运行良好,我可以成功上传 CSV 文件并使用 Pandas 数据框读取它。但我将 csv 保存在本地文件系统中并读取它。
我试过像下面这样阅读 -
files = request.files['file']
files.read()
Run Code Online (Sandbox Code Playgroud)
获得的结果是字节格式,但我需要字典格式。因此,我使用 Pandas 数据框来读取它,然后将其转换为我的格式的自定义字典。
是否可以在不将其写入本地文件系统的情况下即时读取 CSV 文件?或者我们可以使用 Python Flask Restful 实现的任何等效方法?
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData
Run Code Online (Sandbox Code Playgroud)
This is my function for converting an image to binary...
uploaded_file = request.files['file']
if uploaded_file.filename != '':
uploaded_file.save(uploaded_file.filename)
empPicture = convertToBinaryData(uploaded_file)
Run Code Online (Sandbox Code Playgroud)
and this is the block of code where the uploaded file is received and saved, however, when it runs, I get this error...
with open(filename, 'rb') as file:
TypeError: expected str, bytes or os.PathLike object, not FileStorage
Run Code Online (Sandbox Code Playgroud)
I'm pretty new …
如果我在Python中输入:
open("file","r").read()
Run Code Online (Sandbox Code Playgroud)
有时它会将文件的确切内容作为字符串返回,有时它会返回一个空字符串(即使文件不为空).有人可以解释一下这取决于什么?
我的代码当前接收一个文件,并将其保存到预设目录,但是可以只使用该文件(读取文件)而不保存它吗?
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "yatta"
else:
return "file not allowed"
return render_template("index.html")
Run Code Online (Sandbox Code Playgroud)
我试过了两个
file.read()和file.stream.read()但是返回值为空.我验证该文件是否存在于上载的目录中,并看到该文件不为空.