为什么这个Python循环无法输出到下一个可用的Excel行?

首先,最重要的是:提前感谢您的帮助。 我是一个总编程新手,我的代码将反映这一点。 我将尝试描述我正在尝试做什么,并显示代码。 再次感谢您的时间和解释。

目标:我想让python打开一个现有的excel文件(output.xls),然后在该文档的下一个可用行中input一个值(在这种情况下,'testing文本')。 我试图使用'while'循环和'if'语句来完成这个任务。 虽然既不返回错误,也不能正确地将输出移动到第二行。 这是我得到的。

from xlrd import open_workbook from xlutils.copy import copy import xlwt wb = open_workbook('output.xls',formatting_info=True) sheet = wb.sheet_by_name("sheet 1") #This is the simple test text here. a = 'just a test' rb = copy(wb) ws = rb.get_sheet(0) row = 0 cell = sheet.cell(row,4) 

我在下面想说的是-WHILE-单元格不是空白的(types6),然后在行中加一个并重复。 IE:继续下去,直到你在第四栏中空白。

 while cell.ctype != 6: row = row + 1 ws.write(row,4,a) 

在这里,我希望确认结果。

 print cell.ctype rb.save('output.xls') 

无论如何,当我运行代码时,它似乎并没有超过第一行。 就好像代码所说的那样,“很好,第一个单元不是第六类”,但是没有超越这个。 尽pipe在网上search了数小时,但我似乎无法find原因。

任何帮助/指导非常感谢。

—编辑—

以下是我收到的build议回复中的错误。 错误是相同的。

 Traceback (most recent call last): File "C:\Users\Administrator\Desktop\Folder", line 19, in <module> cell = sheet.cell(row,4) File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 395, in cell xfx = self.cell_xf_index(rowx, colx) File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 421, in cell_xf_index xfx = self._cell_xf_indexes[rowx][colx] IndexError: list index out of range 

你永远不会移动到下一个单元格。 只是改变variablesrow不影响cell 。 试试这个代码:

 cell = sheet.cell(row,4) while cell.ctype != 6: row = row + 1 if row >= sheet.nrows: break cell = sheet.cell(row,4) # <-- actually move the "pointer" in the excel sheet 

你提前行索引 – 但你不读一个新的单元格,所以你的单元格保持不变,你进入一个无限循环

 while cell.ctype != 6: row = row + 1 cell = sheet.cell(row,4) 

应该pipe用

编辑:

你正在用尽行 – 很容易修复

 try: while cell.ctype != 6: row = row + 1 cell = sheet.cell(row,4) except IndexError: <do something> 

就我个人而言,我觉得你跑得太快了 – 你正在试图在没有学习基础知识的情况下变得太深