2017-02-28 132 views
2

我在Python中有這段代碼,應該可以工作。Python循環無法正常工作(xlwt)

python 

import xlwt 

#== change variables according to requirements ==# 

numoftopcol = 5 

numoftestcases = 4 

coltext = ['Test Case', 'Test Name', 'Duration', 'Factual Result', 'Result (Pass/Fail)'] 

testN = ['void','Get Counter Result', 'Read Stats', 'Client Initialization', 'Start Server'] 

#== change variables according to requirements ==# 

styleH = xlwt.easyxf('font: name Arial, bold on, color-index blue;') 

styleH.font.height = 400 

stylee = xlwt.easyxf('font: name Arial') 

wb = xlwt.Workbook() 

ws = wb.add_sheet('Test Case Overview') 

c = 0 

numoftopcol += 1 

for c in range(c,numoftopcol): 

    ws.write(0, c, coltext[c], styleH), 

    ws.col(c).width = 7000 


import random 

c = 1 

numoftestcases += 1 

for c in range(c,numoftestcases): 

    strC = str(c), 

    ws.write(c,0,'TC-'+strC,stylee), 

    ws.write(c,1,testN[c],stylee), 

    ws.write(c,2,'DUR',stylee), 

    ws.write(c,3,'RandomStr',stylee), 

    randomint = random.randint(0,1), 

    if randomint == 0: 

      ws.write(c,4,'PASS',stylee) 

    else: 

      ws.write(c,4,'FAIL',stylee) 

現在,第一個週期工作正常(styleH)。第二個不工作(stylee)。調試我發現,c = 1和numoftestcases = 5。所以如果c < numoftestcases或1 < 5,那麼週期應該是工作,對吧?

顯然它沒有。我在cmd中得到以下錯誤輸出(對於第二個循環)。

forTraceback (most recent call last): File "", line 2, in IndexError: list index out of range

Traceback (most recent call last): File "", line 3, in TypeError: cannot concatenate 'str' and 'tuple' objects

這是什麼問題? 早先這個工作我記得。我沒有改變循環代碼,但現在它不工作。

我也嘗試在第二個週期的第一行放置一個打印(c),輸出僅爲1.沒有更多的數字跟在後面。

檢查xls文件,只有第一個週期寫在電子表格中。

我將這段代碼存儲在一個文本文件中,所以我可以隨時在cmd中調用此命令。

回答

3

首先:指標超出範圍:您定義numoftopcol至5這是列表的len,只是你增加它的循環之前...現在進入這個指數收益率超出範圍......

錯誤的根本原因是excel座標從1開始,但python列表是0索引的。我會做從0n的循環,並且只爲xlwt的呼叫添加1,而不是做所有您要做的+1

二:串聯錯誤:你沒有張貼任何堆棧跟蹤,但

strC = str(c), 

創建一個tuple。下一行:

ws.write(c,0,'TC-'+strC,stylee), 

試圖將str添加到tuple

+0

我可以看到,但我該如何解決這個問題? numoftopcol不會導致問題,但numoftestcases會。 – Unit1

+0

'numoftopcol'超出範圍並跳過第一個元素。郵政堆棧跟蹤,如果你想更好的診斷 –

0

我發現了什麼問題。我必須將cnumoftestcases的數據類型轉換爲int。

int(c) 
int(numoftestcases) 

案件解決。現在正在工作。