繁体   English   中英

Python“ IndexError:列表索引超出范围” 目标:读取1个excel文件并将数据附加到第二个excel文件

[英]Python “IndexError: list index out of range” | Goal: Read 1 excel file & append data to a 2nd excel file

该脚本的目标是从每天由cron作业生成的excel文件中获取数据,并将该数据附加到“主” excel文件的底部。

这是我现在的位置:

# Find the most recent excel file created by the cron job & open it.

localtime = time.localtime(time.time())
yy = localtime.tm_year
mm = localtime.tm_mon
dd = localtime.tm_mday

file_name = 'daily_' + str(yy) + '_' + str(mm) + '_' + str(dd-1) + '.xls'
file_loc = '/Users/' + file_name
new_sheet = open_workbook(file_loc, on_demand=True).sheet_by_index(0)

# Grab all the data from the recent cron job file starting at row 2 to avoid
# including headers.

for row in range(1, new_sheet.nrows):
    values = []
    for col in range(new_sheet.ncols):
        values.append(new_sheet.cell(row,col).value)
"""
The above loop structures the list 'values[]' in a way that the print
statement of value looks like the below output; which matches the formatting of 
master_file.xlsx:

        2341511  Sports 12112 Dog   324.92
        71611    Other  18192 Cat   128.17
        ...
"""

# Find the excel master file & open it.

sheet = open_workbook('master_file.xlsx').sheet_by_index(0)

# Find the first row that is empty.
new_row = sheet.nrows + 1

# Append the values[] list to the master file starting at row(new_row) and save
# the db file.

for row_num, row in enumerate(values, new_row):
    for col_num, col in enumerate(row):
        sheet.row(row_num).write(col_num, col)

sheet.save('master_file.xlsx')

我的回溯错误是:

File "daily.py", line 45, in <module>
    sheet.row(row_num).write(col_num, col)
  File "/Users/code/env/lib/python2.7/site-packages/xlrd/sheet.py", line 462, in row
    for colx in xrange(len(self._cell_values[rowx]))
IndexError: list index out of range

任何帮助将不胜感激!

该代码的直觉是您实际上没有在迭代之前向工作表添加一行。

xlrd看起来并不真正具有修改现有工作表的方法。 请查看此SO帖子,这可能会有所帮助...

如何使用xlrd将新的列和行添加到.xls文件

您是说要使用col(new_row)而不是col ,例如:

for row_num, row in enumerate(values, col(new_row)):
    for col_num, col(new_row) in enumerate(row):
        sheet.row(row_num).write(col_num, col(new_row))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM