2016-11-14 50 views
-1

我有這個劇本上的Python 2.6 RHEL OS:IndexError:從列表索引超出範圍讀/寫/到文件

import csv 

def write_cols(data): 
    col_spacer = " "  # added between columns 
    widths = [0] * len(data[0]) 

    for row in data: 
     widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)] 

    return [col_spacer.join("{0:<{1}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 


with open('pathtofile/input.csv', 'rb') as f_input: 
    with open('pathtofile/output.txt', 'w') as f_output: 
       rows = list(csv.reader(f_input, delimiter='\t')) 
    for row in write_cols(rows): 
      f_output.write(row + '\n') 

但我得到這個錯誤:

Traceback (most recent call last): 
    File "format.py", line 26, in <module> 
    for row in write_cols(rows): 
    File "format.py", line 19, in write_cols 
    return [col_spacer.join("{{:<{width}}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 
    File "format.py", line 19, in <genexpr> 
    return [col_spacer.join("{{:<{width}}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 
IndexError: list index out of range 
莫非

有人幫我解決這個問題? 我已經寫了關於Python 2.7這個腳本,它工作得很好,現在我試圖讓adjustements到2.6

+1

小清理筆記:儘量保持您的縮進一致的4個空格。 'with'語句會自動關閉你的文件,不需要以後關閉它們。無論如何,您的'close'語句沒有任何影響,因爲您只是列出方法而不是調用它。 – Billy

+0

[ValueError:具有讀寫形式的零長度字段名稱]的可能重複(http://stackoverflow.com/questions/40587912/valueerror-zero-length-field-name-in-format-with-read-and -write) – Ayoub

+0

它總是我,但我有另一種錯誤@Ayoub –

回答

0

您的格式來電來訪運行:

"{{:<{width}}}".format(col, width=widths[index]) 

有太多或沒有足夠的參數/括號。字符串中的大括號每個都表示放置format的文本的位置。我會說你有太多的大括號,它會因此而感到困惑。你既可以使用不同的括號,或者刪除它們......

告訴我,如果我錯過了這句話的點/目的

+0

剛編輯修改這部分的問題,但我有同樣的錯誤。 –

0

您需要將此

"{:<{width}}".format(col, width=widths[index]) 

改變這個

"{0:<{1}}".format(col, widths[index]) 

它會工作。

+0

這個改變給了我這個錯誤:IndexError:元組索引超出範圍。任何提示? –

0

我在@MartinEvans的幫助下解決了問題。

問題比我們想象的要簡單:輸入文件底部有一個空行。

相關問題