Skip to content
Advertisement

Try and Catch Exception not working as expected using pyodbc in python

Goal: Write a script which will read a file line by line and then insert it into the database. The line should be written to a log file if the insertion fails

Problem to solve for: It appears if the line cannot be inserted, my print statement works which is “Failed to insert into the product table” but the line not inserted should be written to a text file called log.txt. It appears only one of those lines are being inserted and none of the others are written to log file.

Can someone please suggest what is wrong with my try/catch exception? It should be writing all non inserted lines to the log file

JavaScript

Advertisement

Answer

You are opening the log file in write mode each time there is an exception. This means you begin writing at the beginning of the file, overwriting anything previously written to it.

You should open in append mode instead, so that you start writing at the end of the file. Change "w" to "a" in your open() call.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement