我有這個劇本上的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
小清理筆記:儘量保持您的縮進一致的4個空格。 'with'語句會自動關閉你的文件,不需要以後關閉它們。無論如何,您的'close'語句沒有任何影響,因爲您只是列出方法而不是調用它。 – Billy
[ValueError:具有讀寫形式的零長度字段名稱]的可能重複(http://stackoverflow.com/questions/40587912/valueerror-zero-length-field-name-in-format-with-read-and -write) – Ayoub
它總是我,但我有另一種錯誤@Ayoub –