[英]Limiting row numbers with Python (CSV Reader)
我想在下面的 python 代碼中限制行數,如果行數少於 200 則執行代碼,如果行數超過 200 則不運行代碼。使用以下代碼,我正在打印行數,但 if 子句限制行給了我錯誤。
TypeError:視圖 function 未返回有效響應。 function 要么返回 None 要么在沒有返回語句的情況下結束。
錯誤:索引:/ CreateStudent [GET] 上的異常
我在瀏覽器中看到的內容:服務器遇到內部錯誤,無法完成您的請求。 服務器過載或應用程序出錯。
@app.route('/CreateStudent', methods=['GET','POST'])
def upload_student():
if request.method == 'POST':
csv_file = request.files['file']
if not csv_file:
return render_template('error.html')
csv_file = TextIOWrapper(csv_file, encoding='utf-8')
csv_reader = csv.reader(csv_file)
lines= list(csv_reader)
print(lines)
if len(lines) < 200:
for row in lines:
if len(row)==4:
name=row[0]
familyname=row[1]
age=row[2]
job=row[3]
create_student(name,familyname,age,job)
time.sleep(2)
return render_template('success.html')
return render_template('CreateStudent.html')
當我還想打印行時,我看到我的結果如下: [['Sara','Jacky','22','engineer']] 為什么我的結果中有這個 2 [[]],是因為名單?
在這里,我稍微修改了您的代碼,並在我進行修改的地方添加了注釋:
if request.method == 'POST':
csv_file = request.files['file']
if not csv_file:
return render_template('error.html')
csv_file = TextIOWrapper(csv_file, encoding='utf-8')
csv_reader = csv.reader(csv_file)
lines = list(csv_reader) # <--- read the file into `lines`
if len(lines) < 200:
for row in lines: # <-- we're iterating over `lines` now
if len(row)==4:
create_Student(*row) # <-- no need to extract to variables, simple `*` is enough
return render_template('success.html')
return render_template('CreateStudent.html') # <-- this is returned in case len(lines) >= 200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.