Populate Excel from Python list

1k Views Asked by At

I want to populate a excel sheet with data read from a text file. My script opens a text file and then puts certain attributes into a list. I then want to populate my excel sheet with data in the list.

I have many txt documents in the same location so my script loops though the files.

What is wrong with my code ? It only populates one row.

import xlwt
import os


output = 'D:\Holding_Area\\test.xls'
file_path='Y:\\Testing\\Crashes'
pathappend=[]
r=1

for a in os.listdir(file_path):
    pathappend.append(file_path+'\\'+a)


def main():
    for x in pathappend:   
        appendlist=[]
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('python', cell_overwrite_ok=True)    
        file = open(x)
        lines = file.readlines()
        appendlist.append(lines[1][2:10])
        appendlist.append(lines[1][13:21])
        appendlist.append(lines[4][15:30])
        appendlist.append(lines[10][13:22])
        appendlist.append(lines[11][9:28])
        appendlist.append(lines[22])
        appendlist.append(lines[31][84:113])
        appendlist.append(lines[27:29])
        file.close()
        for i,e in enumerate(appendlist):
            sheet.write(r,i,e)  
            r+1


        wbk.save(output)
main()
1

There are 1 best solutions below

0
On BEST ANSWER

Issue was with the 'r+1' it should be 'r+=1'; as shown below:

import xlwt
import os


output = 'D:\Holding_Area\\test.xls'
file_path='Y:\\Testing\\Crashes'
pathappend=[]
r=1

for a in os.listdir(file_path):
    pathappend.append(file_path+'\\'+a)


def main():
    for x in pathappend:   
        appendlist=[]
        wbk = xlwt.Workbook()
        sheet = wbk.add_sheet('python', cell_overwrite_ok=True)    
        file = open(x)
        lines = file.readlines()
        appendlist.append(lines[1][2:10])
        appendlist.append(lines[1][13:21])
        appendlist.append(lines[4][15:30])
        appendlist.append(lines[10][13:22])
        appendlist.append(lines[11][9:28])
        appendlist.append(lines[22])
        appendlist.append(lines[31][84:113])
        appendlist.append(lines[27:29])
        file.close()
        for i,e in enumerate(appendlist):
            sheet.write(r,i,e)  
            r+=1


    wbk.save(output)
main()