I am trying to create a record from a list of 6 items. The error tells me that rec[1] is out of range.
pay = open("paymast.txt","r")
sal = open("saltyp.txt","w")
heading = pay.readline()
for rec in pay:
rec = rec.split(",")
id = rec[0]
name = rec[1]
gender = rec[2]
code = rec[3]
grade = rec[4]
salary = rec[5]
salary = salary.strip('\n')
record = id+","+name+","+gender+","+code+","+grade+","+salary
if int(salary) < 1500 and gender == "M":
sal.write(record)
pay.close()
sal.close()
Try to check your file paymast.txt
. I've tried with an array of string, formatted as "id,name,..."
and the split works fine, the only time that it raises an IndexError
is when the input is bad formatted.
For example:
pay = ["1", "0,ted,male,4,23,1440\n",
"2,katie,female,1,2,240\n"]
# The first index should raise the error
for rec in pay:
rec = rec.split(",")
id = rec[0]
name = rec[1]
gender = rec[2]
code = rec[3]
grade = rec[4]
salary = rec[5]
salary = salary.strip('\n')
record = id+","+name+","+gender+","+code+","+grade+","+salary
print(record)
Raised error:
Traceback (most recent call last):
File "so.py", line 9, in <module>
name = rec[1]
IndexError: list index out of range
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments