python - 我无法在 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, row=row,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, 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, row=row,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","RIG MOVE","RIG COMMISSIONING","ABANDONMENT","LEARNINGCURVE"]:
crud.insert_sequence_record(db=db, row=row,is_drilling=False)
else:
crud.insert_sequence_record(db=db, row=row,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'))
推荐阅读
- xml - 如何处理所有只有文本而没有子节点的节点?
- html - 如何在以下演示的右侧添加图像?
- c - c编程 - 从文件中提取数据字符串
- python - Python方法编码:本地名称是否可以引用属性以避免重复self.attribute?
- c# - 如何在观看节目前显示 LoginPage?
- c# - EntityFramework 调用 scaler 函数抛出 必须声明标量变量
- javascript - 拖动父元素后传单“dragend”事件处理程序丢失
- python - 如何从熊猫系列中查询经度以获得期望值?
- reactjs - 如何动态调整 React chart 2 饼图的大小
- c# - 下载不正确的 xlsx 文件