IndexError:列表索引超出读/写文件的范围

时间:2016-11-14 13:09:59

标签: python

我在RHEL OS的Python 2.6上有这个脚本:

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上编写了这个脚本并且工作正常,我现在正在尝试调整以在2.6上运行

3 个答案:

答案 0 :(得分:0)

您的格式来电:

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

有太多或没有足够的参数/大括号。字符串中的大括号各表示放置format文本的位置。我说你有太多的牙套,它会被它弄糊涂。您可以使用不同的括号,也可以删除它们......

告诉我,我是否错过了本声明的要点/目的

答案 1 :(得分:0)

您需要更改此

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

到这个

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

它会起作用。

答案 2 :(得分:0)

我在@MartinEvans的帮助下解决了。

问题比我们想象的要简单:输入文件底部有一个空行。

相关问题