Search code examples
pythonpython-3.xlistrowcsvreader

Limiting row numbers with Python (CSV Reader)


I want to give limitation in row numbers in the below python code, executing code if we have less than 200 rows and nit run the code if it is more than 200. with below code, I am printing the number of rows but the if clause for limiting rows gives me error.

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

ERROR:index:Exception on /CreateStudent[GET]

What i see in the browser: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

@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')

when i want to also just print lines i see my result as below: [['Sara','Jacky','22','engineer']] why i have this 2 [[]] in my result, is it because of list?


Solution

  • Here I slightly modified your code and added comments where I've made a modification:

    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