如何解决列表索引错误Python?

时间:2020-06-09 08:38:22

标签: python

我在目录中通过python.excel文件进​​入Excel报告目录。我的代码可以运行,但是当我将其转换为函数时报错=“列表索引超出范围”这是我的代码,然后转换为函数:

xfile = openpyxl.load_workbook('C:/Users/11359023/Desktop/movemail_project/report_ie.xlsx')
sheet = xfile.get_sheet_by_name(cut_name_sheet("D:/UAT Move mail/01-FIN & ACC-Confidential/Inbound/IE-Direct/"))
#Header
sheet['A2'].value = "Property Files Report as at "  + str(d1)
sheet['A4'].value = "Files"
sheet['B4'].value = "Source path"
sheet['C4'].value = "Destination path"

x=5
col = "A"
row = x
y=5
col2 = "B"
row2 = y
for root, dirs, files in os.walk("D:/UAT Move mail/01-FIN & ACC-Confidential/Inbound/IE-Direct/"): 
    for file in files:
        if file.lower().endswith('.pdf'):
            sheet['{0}{1}'.format(col, row)].value = file
            row += 1
            sheet['{0}{1}'.format(col2, row2)].value = root+"/"+str(file)
            row2 += 1
            xfile.save('report_ie_x.xlsx')

This's my Excel report output.

这是我转换为函数时的代码:

def report_copyie(z): 
    xfile = openpyxl.load_workbook('C:/Users/11359023/Desktop/movemail_project/report_ie.xlsx')
    sheet = xfile.get_sheet_by_name(cut_name_sheet(z))
    #Header
    sheet['A2'].value = "Property Files Report as at "  + str(d1)
    sheet['A4'].value = "Files"
    sheet['B4'].value = "Source path"
    sheet['C4'].value = "Destination path"
    x=5
    col = "A"
    row = x
    y=5
    col2 = "B"
    row2 = y
    for root, dirs, files in os.walk(z): 
        for file in files:
            if file.lower().endswith('.pdf'):
                sheet['{0}{1}'.format(col, row)].value = file
                row += 1
                sheet['{0}{1}'.format(col2, row2)].value = root+"/"+str(file)
                row2 += 1
                xfile.save('report_ie_x.xlsx') 

请告诉我是什么问题?

1 个答案:

答案 0 :(得分:0)

由于我们在您的问题中没有堆栈跟踪,因此我会猜测全部来源

错误“列表索引超出范围”与在错误索引处访问列表有关-有关详细信息,请参见以下答案:Index Error: list index out of range (Python)

在您的情况下,您正在以列表的形式访问工作表,我认为在将代码重新编写为函数时,工作表未正确打开或该文件发生了某些情况。因此,请确保您的工作表(文件)存在并且可以使用索引

进行访问