I have an excel book with a couple of sheets. Each sheet has two columns with
LegacyID. We are basically trying to update some records in the database based on
personid. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying to learn Python, I thought I would try this in Python. I used
xlrd module and I was able to print update statements. below is my code:
import xlrd book = xlrd.open_workbook('D:\Scripts\UpdateID01.xls') sheet = book.sheet_by_index(0) myList =  for i in range(sheet.nrows): myList.append(sheet.row_values(i)) outFile = open('D:\Scripts\update.txt', 'wb') for i in myList: outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i) + "'" + " WHERE personid = " + "'" + str(i) + "'")
Two problems – when I read the output file, I see the
LegacyID printed as float. How do I get rid of
.0 at the end of each id? Second problem, python doesn’t print each update statement in a new line in the output text file. How to I format it?
Edit: Please ignore the format issue. It did print in new lines when I opened the output file in Notepad++. The float issue still remains.
Can you turn the LegacyID into ints ?
i = int(i)
outFile.write(“\nUPDATE PERSON SET LegacyID = ” + “‘” + str(i) + “‘” + ” WHERE personid = ” + “‘” + str(i)
# use 'a' if you want to append in your text file outFile = open(r'D:\Scripts\update.txt', 'a') for i in myList: outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i), str(i)))
Since you are learning Python (which is very laudable!) you should start reading about string formatting in the Python docs. This is the best place to start whenever you have a question light this.
Hint: You may want to convert the float items to integers using