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}
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}
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}
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}