python - How to read data from Excel and write it to text file line by line? -


i want write code data excel , write text file. here code have:

import xlrd import os.path wb = xlrd.open_workbook(os.path.join('d:\trb 2014 data','sps1 demo data.xlsx')) wb.sheet_names() sh = wb.sheet_by_index(0) = 1  while sh.cell(i,11).value != 0:     load = sh.cell(i,11).value    d1 = sh.cell(i,13).value    d2 = sh.cell(i,14).value    d3 = sh.cell(i,15).value    d4 = sh.cell(i,16).value    d5 = sh.cell(i,17).value    d6 = sh.cell(i,18).value    d7 = sh.cell(i,19).value    db1 = str(load) + "  " + str(d1) + "  " + str(d2) + "  " + str(d3)+ "  " + str(d4)+ "  " + str(d5)+ "  " + str(d6)+ "  " + str(d7)     file = open("output.txt", "w")    file.write(db1 + '\n')    file.close    = + 1 

the problem code data written text file displayed @ first row. therefore, although have 20 rows of data in excel, text file shows last data in excel file @ first row in text file. have '\n' in file.write but, doesn't seem work.

you should open output.txt file append mode:

file = open("output.txt", "a") 

also, should before entering loop, , should closed after loop.


update:

in cases one, use with instead of closing file handle @ end.

also including suggestion made @josh in own answer, code this:

import xlrd import os.path  wb = xlrd.open_workbook(os.path.join('d:\trb 2014 data','sps1 demo data.xlsx')) wb.sheet_names() sh = wb.sheet_by_index(0) = 1 open("output.txt", "a") my_file:     while sh.cell(i,11).value != 0:         load = sh.cell(i,11).value         all_d = sh.col_values(i, 13, 19)         db1 = load + " " + (" ".join(all_d))         my_file.write(db1 + '\n')         += 1 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -