如何解决我无法在FastAPI中读取上传的CSV文件
我正在尝试遍历一个csv文件。但是,收到的文件很难读取。我进行了搜索,找不到清晰的解决方案!
@app.get("/uploadsequence/")
async def upload_sequence_form():
return HTMLResponse("""
<!DOCTYPE html>
<html>
<head>
<title>sequence upload</title>
</head>
<body>
<h1>upload sequence .CSV file</h1>
<form method='post' action='/uploadsequence/' enctype='multipart/form-data'>
Upload a csv file: <input type='file' name='csv_file'>
<input type='submit' value='Upload'>
</form>
</body>
</html>
""")
@app.post("/uploadsequence/")
async def upload_sequence(csv_file: UploadFile = File(...),db = Depends(get_db)):
csv_file_encoded = TextIOWrapper(csv_file.file,encoding='utf-8')
csv_reader = csv.DictReader(csv_file_encoded)
for row in csv_reader:
if row["Well Type"] in ["RIG MAINTENANCE","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
crud.insert_sequence_record(db=db,row=row,is_drilling=False)
else:
crud.insert_sequence_record(db=db,is_drilling=True)
它给了我这个错误:
csv_file_encoded = TextIOWrapper(csv_file.file,encoding='utf-8') AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'
我将UploadFile
更改为bytes
:
@app.post("/uploadsequence/")
async def upload_sequence(csv_file: bytes = File(...),db = Depends(get_db)):
csv_file_encoded = TextIOWrapper(csv_file,is_drilling=True)
出现此错误:csv_file_encoded = TextIOWrapper(csv_file,encoding='utf-8') AttributeError: 'bytes' object has no attribute 'readable'
我摆脱了编码:
@app.post("/uploadsequence/")
async def upload_sequence(csv_file: bytes = File(...),db = Depends(get_db)):
# csv_file_encoded = TextIOWrapper(csv_file,encoding='utf-8')
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
if row["Well Type"] in ["RIG MAINTENANCE",is_drilling=True)
出现此错误:
self._fieldnames = next(self.reader) _csv.Error: iterator should return strings,not int (did you open the file in text mode?)
解决方法
我使用以下内容读取了csv文件。 codecs.iterdecode
为我工作。
csv_reader = csv.reader(codecs.iterdecode(csv_file.file,'utf-8'))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。