save button: IndexError - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: save button: IndexError (/thread-30553.html) |
save button: IndexError - Maryan - Oct-25-2020 So my app can successfully export to csv file and import it. But when I try to save the data into the DB I'm getting error. One note: when I import the csv file there is extra one empty row. IndexError: list index out of range Here is my function for save buton def savedb(): if messagebox.askyesno('Confirm', 'Are you sure you want to save the data into the Database?'): try: for i in mydata: sid = i[0] fname = i[1] surname = i[2] idc = i[3] query = "INSERT INTO student_questioner(student_id, student_name, student_surname, student_card, student_score) VALUES (NULL, ?, ?, ?,?) " cur.execute(query, (sid,fname, surname, idc)) con.commit() clear() messagebox.showinfo('Data Saved', 'Data has been saved to the database!') except EOFError as a: messagebox.showerror(a) else: return False RE: save button: IndexError - bowlofred - Oct-25-2020 The error should have the line number its from, not just the error. Somewhere you are using an index, like line6, sid=i[0]. There the 0 is the index into the collection i. But since i is created from mydata, and mydata isn't defined here, there's no way to tell how many elements it has If it has less than 4 elements, then one of lines 6 through 9 will generate an error. You might want to print out either the collection or the length of the collection to see if it's what you expect. RE: save button: IndexError - Maryan - Oct-26-2020 I found the solution. The error was when I export the CSV file, which has extra empty row.I fix this with "lineterminator='\n'". I have some another bug to fix now, when I save the file, the file doesn't have extension after the name. Even I add *.csv extension before it save the file :\ fln = filedialog.asksaveasfilename(initialdir = os.getcwd(), title = 'Save CSV', filetypes = (("CSV File", "*.csv"), ("All Files", "*.*"))) (Oct-25-2020, 11:40 PM)bowlofred Wrote: The error should have the line number its from, not just the error. RE: save button: IndexError - bowlofred - Oct-26-2020 Try adding the defaultextension option. fln = filedialog.asksaveasfilename(initialdir = os.getcwd(), title = 'Save CSV', filetypes = (("CSV File", "*.csv"), ("All Files", "*.*")), defaultextension=True) RE: save button: IndexError - Maryan - Oct-26-2020 It is working smoothly now :) Thank you! (Oct-26-2020, 01:05 AM)bowlofred Wrote: Try adding the defaultextension option. |