从 Python 列表中填充 Excel

Populate Excel from Python list

我想用从文本文件读取的数据填充 excel sheet。 我的脚本打开一个文本文件,然后将某些属性放入列表中。然后我想用列表中的数据填充我的 excel sheet。

我在同一个位置有很多 txt 文档,所以我的脚本会循环遍历这些文件。

我的代码有什么问题?它只填充一行。

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()

问题出在 'r+1' 上,应该是 'r+=1';如下图:

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()