我正在尝试创建一个API函数,它接受.csv文件(上传)并以熊猫DataFrame的形式打开它。就像这样:
from fastapi import FastAPI
from fastapi import UploadFile, Query, Form
import pandas as pd
app = FastAPI()
@app.post("/check")
def foo(file: UploadFile):
df = pd.read_csv(file.file)
return len(df)
然后,我调用我的API:
import requests
url = 'http://127.0.0.1:8000/check'
file = {'file': open('data/ny_pollution_events.csv', 'rb')}
resp = requests.post(url=url, files=file)
print(resp.json())
但我犯了这样的错误:FileNotFoundError: [Errno 2] No such file or directory: 'ny_pollution_events.csv'
据我从文档了解到,熊猫能够从类似文件的对象中读取.csv文件,file.file
应该是这样的。但是,在这里,在read_csv()方法中,熊猫获得名称(而不是文件对象本身),并试图在本地找到它。
我做错了什么吗?我能以某种方式实现这个逻辑吗?
发布于 2022-05-22 11:17:32
若要在熊猫中读取该文件,必须将该文件存储在您的PC上。不要忘记导入shutil
。如果您不需要将该文件存储在您的PC上,请使用os.remove(filepath)
删除它。
if not file.filename.lower().endswith(('.csv',".xlsx",".xls")):
return 404,"Please upload xlsx,csv or xls file."
if file.filename.lower().endswith(".csv"):
extension = ".csv"
elif file.filename.lower().endswith(".xlsx"):
extension = ".xlsx"
elif file.filename.lower().endswith(".xls"):
extension = ".xls"
# eventid = datetime.datetime.now().strftime('%Y%m-%d%H-%M%S-') + str(uuid4())
filepath = "location where you want to store file"+ extension
with open(filepath, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
if filepath.endswith(".csv"):
df = pd.read_csv(filepath)
else:
df = pd.read_excel(filepath)
except:
return 401, "File is not proper"
https://stackoverflow.com/questions/72329302
复制相似问题