IndexError,但更可能是I / O错误

时间:2014-03-31 12:03:08

标签: python-2.7

不确定我收到此错误的原因。我从一个名为columns_unsorted.txt的文件中读取,然后尝试写入columns_unsorted.txt。在fan_on = string_j [1]上有错误,说列表索引超出范围。这是我的代码:

#!/usr/bin/python

import fileinput
import collections

# open document to record results into
j = open('./columns_unsorted.txt', 'r')
# note this is a file of rows of space-delimited date in the format <1384055277275353 0 0 0 1 0 0 0 0 22:47:57> on each row, the first term being unix times, the last human time, the middle binary indicating which machine event happened

# open document to read from
l = open('./columns_sorted.txt', 'w')

# CREATE ARRAY CALLED EVENTS
events = collections.deque()
i = 1

# FILL ARRAY WITH "FACTS" ROWS; SPLIT INTO FIELDS, CHANGE TYPES AS APPROPRIATE
for line in j:      # columns_unsorted
    line = line.rstrip('\n')
    string_j = line.split(' ')
    time = str(string_j[0])
    fan_on = int(string_j[1])
    fan_off = int(string_j[2])    
    heater_on = int(string_j[3])
    heater_off = int(string_j[4])
    space_on = int(string_j[5])
    space_off = int(string_j[6])
    pump_on = int(string_j[7])
    pump_off = int(string_j[8])
    event_time = str(string_j[9])

    row = time, fan_on, fan_off, heater_on, heater_off, space_on, space_off, pump_on, pump_off, event_time
    events.append(row)

2 个答案:

答案 0 :(得分:1)

您缺少readlines功能,没有?

你必须这样做:

 j = open('./columns_unsorted.txt', 'r')
 l = j.readlines()
 for line in l:
     # what you want to do with each line

将来,您应该打印一些变量,以确保代码按照您的意愿运行,并帮助您识别问题。 (例如,如果在你的代码中你会print string_j,你会看到你遇到了什么样的问题)

答案 1 :(得分:0)

问题是数据文件中的不一致行。请原谅我发布的匆忙