Issue
How could I convert a file into a dataframe using the following code?
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
df = pd.read_csv("")
print(df)
return {"filename": file.filename}
Solution
Option 1
Convert the bytes into a string and then load it into an in-memory text buffer (i.e., StringIO
), which can be converted into a dataframe:
from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import StringIO
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
contents = await file.read()
s = str(contents,'utf-8')
data = StringIO(s)
df = pd.read_csv(data)
data.close()
return {"filename": file.filename}
Option 2
Use an in-memory bytes buffer instead (i.e., BytesIO
), thus saving you the step of converting the bytes into a string:
from fastapi import FastAPI, File, UploadFile
import pandas as pd
from io import BytesIO
app = FastAPI()
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
contents = await file.read()
data = BytesIO(contents)
df = pd.read_csv(data)
data.close()
return {"filename": file.filename}
Answered By - Chris Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.