Reputation: 35
I'm still a beginner how do I get rid of this error in my code, I have to print all the names and surnames in a text file this is my code
with open("DOB.txt", "r+", encoding="cp1252") as file:
content = file.read().split("\n")
for line in content:
names = line.split()
print(names[0] + " " + names[1])
it prints out all the names and surnames but still gives the error
Kelly Gardner
Cristina Ortega
Guy Carr
Geneva Martinez
Ricardo Howell
Bernadette Rios
Traceback (most recent call last):
File "C:\Users\27711\Desktop\PROGRAMMING\Bootcamp\compulsary_task.py", line 6, in <module>
print(names[0] + " " + names[1])
IndexError: list index out of range
I've tried removing the \n in the split ontop but it still gives me a error after it prints the names and surnames
Upvotes: 0
Views: 61
Reputation: 146
just put it after for loop starts
if line!='':
names = line.split()
print(names[0] + " " + names[1])
The problem is /n at the end and you are trying to go through that
Also its possible the name has only one element or is empty, and you trying to access it. so you should just insert an If statement either after for loop starts or after this "names = line.split()".
Upvotes: 1
Reputation: 874
The error you are getting is due to you attempting to pull a value that is not there.
The simplest way to solve this is with a try except
for line in content:
try:
names = line.split()
print(names[0] + " " + names[1])
except IndexError as e:
print(e)
Upvotes: 1
Reputation: 23815
Defensive code below
with open("DOB.txt", "r+", encoding="cp1252") as file:
content = file.read().split("\n")
for line in content:
names = line.split()
if len(names) >= 2:
print(names[0] + " " + names[1])
else:
print(f'Not enough fields: {names}')
Upvotes: 2
Reputation:
There are chances that one of the lines doesn't have two names. Proabably one of the lines has only one name. As a result split()
has only one word in it and hence names[1] is out of range error
Upvotes: 0