Home > OS >  Loading text from file into List. Index Error
Loading text from file into List. Index Error

Time:10-12

I have this text file which displays the following information respectively:

ID, name, rate and value

I've entered in this code as shown below, but for some reason when i try to print the name, rate and value fields, it gives me a 'List Index out of Range Error'. The range for ID works perfectly fine, but the others dont. I'm unable to use CSV or any other type of importing tool (due to requirements), so i'm trying to figure out a way to get through this.

 def load_customers(self):
        file = open('customers.txt', 'r')
        i=0
        line = file.readline()
        while(line!=""):
            fields=line.split(', ')
            ID=fields[0]        
            name=fields[1]
            rate=float(fields[2])
            value=float(fields[3])
            self.add_record(ID,name,rate,value)
            line=file.readline()
            i =1
        file.close()
        return (i)

CodePudding user response:

This is because your file has a '\n' line which you are trying to parse.

So Just strip it file.readline().strip():

def load_customers(self):
    file = open('customers.txt', 'r')
    i = 0
    line = file.readline().strip()
    while (line != ""):
        fields = line.split(', ')
        ID = fields[0]
        name = fields[1]
        rate = float(fields[2])
        value = float(fields[3])
        self.add_record(ID, name, rate, value)
        line = file.readline().strip()
        i  = 1
    file.close()
    return (i)

CodePudding user response:

One of the approach in more pythonic way:

def load_customers(self):
    i=0
    with open('customers.txt', 'r') as f:
        for line in f:
            line = line.strip()
            if line:
                fields=line.split(', ')
                ID=fields[0]        
                name=fields[1]
                rate=float(fields[2])
                value=float(fields[3])
                self.add_record(ID,name,rate,value)
                i =1
    return (i)
  • Related