Reputation: 65
Hi i am trying to extract out the information on Column [3] and [4] at row 180. Problem i am facing is
Error it give me: line = reader[180][3] IndexError: list index out of range
@@Data: Source 0 in text format:
1 2 2 1 1 9 1 1 -2 2 1 -3 3 1
3 2 2 1 1 9 1 1 -2 2 1 -3 3 1
4 2 2 1 1 9 1 1 -1 1 1 -2 2 1
reader = list(csv.reader(f, delimiter=' '))
SatIP, CoerIP = getSatHcoer(reader)
print SatIP, CoerIP
def getSatHcoer(reader):
line = reader[180][3]
Sat = line.split(' ')
Sat = Sat[len(Sat)-1]
line = reader[180][4]
Coer = line.split(' ')
Coer = Coer[len(Coer)-1]
return Sat, Coer
pass
Upvotes: 1
Views: 244
Reputation: 61540
If I understand your question correctly, you are having trouble splitting the fields because they are separated by 3 spaces; you can actually split on regular expressions, try using:
Coer = line.split("\s+")
\s
is the regular expression class that represents whitespace (tabs, spaces, newlines, and backspaces?)
+
means apply the previous pattern one or more times, so this expression will match one or more space characters. Using this method, it shouldn't matter how many spaces separate fields.
EDIT As mentioned below this only works if you import re and use re.split.
import re
Coer = re.split("\s+",line)
Upvotes: 1
Reputation: 1048
Keeping in mind that python indexing starts from 0, I'm assuming that when you say line 180, you mean the 181st line in the file and column 3 & 4 are the 4th and 5th columns in the file. If not, -1 from those numbers.
def getSatHcoer(reader):
Sat = reader[180][3]
Coer = reader[180][4]
return Sat, Coer
with open('file.txt', 'r') as f:
reader = [[x.strip().split(' ')] for x in f]
SatIP, CoerIP = getSatHcoer(reader)
print SatIP, CoerIP
Upvotes: 0