Reputation: 543
I'm trying to learn python and delving into string functions. As a simple example, i wrote this
# example line
# username:*:231:-2:gecos field:/home/dir:/usr/bin/false
FILENAME = "/etc/passwd"
filehandle = open(FILENAME, 'r')
lines = filehandle.readlines()
for line in lines:
line = line.rstrip()
fields = line.split(':')
print fields[0]
This example works every time and gives me a username. The first field in the list.
This also works [0:6] and prints all the fields. [:1] prints the username also. [-1] also prints the last field.
The problem is that [1], [-2], [2], and so on result in this error
File "splits.py", line 16, in print fields[-2] IndexError: list index out of range
Am i doing something wrong here? I'm sure it's something silly but the examples i'm looking at say i can do [1], [2], and so on.
I don't think my input is messed up as it's /etc/passwd and [0] and [-1] work.
thanks much.
Upvotes: 3
Views: 814
Reputation: 14251
Sounds like there are some empty lines in your file, maybe at the end.
Example:
>>>line = ''
>>>fields = line.split(":")
>>>print fields[0]
''
>>>print fields[-1]
''
>>>print fields[0:6]
''
>>>print fields[1]
IndexError: list index out of range
You can fix it like this:
for line in lines:
line = line.rstrip()
fields = line.split(':')
if len(fields) == 1:
continue
print fields[0]
Upvotes: 1