Python code, not able to write into xls

a 夏天 提交于 2019-12-02 10:49:31

Your data input has changed. And one or more of its lines contain multiple strings.

If you're reading a file where a line has multiple entires then your str will be a list not a string. If it is a list, this will cause the error when invoking wb.save('example.xls'): TypeError: must be str, not bytes

Here's a pared down version of your program that I used to test this out:

import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
ws_1 = wb.add_sheet('A Test Sheet_B')
cnt_row = 0
cnt_col_1 = 0
cnt_col_2 = 0

f = open('<an xml file with one string per line except the last line which has two strings', 'r', encoding='utf-8')
while 1:

    str = f.readline()
    wb.save('example.xls')
    if str == "":
        print ("file finished")
        break
    str = str.split('<', 1)[1]
    str = str.rsplit('<', 1)
    ws.write(cnt_row, 1, str)
    cnt_row = cnt_row + 1
    print('debug:last')
    print(str)
    print(type(str))

wb.save('example.xls')
f.close()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!