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

Python“;索引器:列表索引超出范围目标:读取1个excel文件&;将数据附加到第二个excel文件,python,excel,xlrd,xlwt,Python,Excel,Xlrd,Xlwt,该脚本的目标是从每天从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 f

该脚本的目标是从每天从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
文件“daily.py”,第45行,在
表.行(行数).写(列数,列数)
文件“/Users/code/env/lib/python2.7/site packages/xlrd/sheet.py”,第462行
对于xrange中的colx(len(自单元值[rowx]))
索引器:列表索引超出范围

任何帮助都将不胜感激

您的意思是使用
col(新行)
而不是
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))

根据代码的直觉,在迭代之前,您实际上并没有向工作表中添加行

xlrd看起来并没有修改现有工作表的方法。看看这篇文章,这可能会有帮助


很抱歉,我发布了错误的for循环。编辑为正确的。但是,两者都给出了索引器。@dudebedies那么这可能是一个off-by-1错误,您是否尝试将索引偏移1?我尝试将新行上的索引在两个方向上偏移1,但没有成功。我想我会继续修补它。我假设我不必在工作表中添加一行,因为所有的书写都是用xlwt&write函数处理的。也许我对xlrd和xlwt一起玩的方式错了。谢谢你的链接。我完全需要xlUtils。耶!祝你好运如果有帮助,请随意标记为已回答和/或向上投票;)