Search code examples
pythondictionarysplitstrip

How to check a string for emptyness or length zero


I recently asked a question about converting list of values from txt file to dictionary list. You can see it from the link here: See my question here


P883, Michael Smith, 1991
L672, Jane Collins, 1992

(added)
(empty line here)
L322, Randy Green, 1992
H732, Justin Wood, 1995(/added)
^key ^name ^year of birth

===============
this question has been answered and i used the following code (accepted answer) which works perfectly:

def load(filename): students = {}

   infile = open(filename)
   for line in infile:
       line = line.strip()
       parts = [p.strip() for p in line.split(",")]
       students[parts[0]] = (parts[1], parts[2])
   return students 


however when there is a line space in the values from the txt file.. (see added parts) it doesnt work anymore and gives an error saying that list index is out of range.


Solution

  • Check for empty lines inside your for-loop and skip them:

    for line in infile:
        line = line.strip()
        if not line:
            continue
        parts = [p.strip() for p in line.split(",")]
        students[parts[0]] = (parts[1], parts[2])