-4

I am learning to write a guardian pattern to prevent empty lists from breaking my code below. I purposely placed a blank line in the txt file to test the guardian pattern.

han = open('file.txt')

for line in han:
    line = line.rstrip()
    wds = line.split(',')

    print(len(wds)) # this is what i used to test the blank line - confirmed this does NOT return 0

    if len(wds) < 1: continue # << This is my guardian pattern

    #if line == '' :
    #    continue
    if wds[5] != 'random string' :
        continue
    print(wds[1])

When I test the len() function directly in the Python shell, it has no problem returning 0 when I input a blank list in the parameter.

However, with my code above, when I use the len() function and insert the blank list 'wds', it seems like len() does not return the 0 and completely skips my guardian pattern which leads to the traceback you would expect if a guardian pattern was not there:

 File "C:\Users\user\Documents>DataStructures_Pt2.py", line 16, in <module>
    if wds[5] != 'random string' :
IndexError: list index out of range

Notice the print() statement before my guardian statement. All lines before my blank line are returning a value. The only line that does not return a value is the blank line. Full output below

C:\Users\User\Documents>DataStructures_Pt2.py
6
6
6
6
6
6
6
6
6
9
6
6
6
6
6
6
6
6
6
6
6
6
6
6
1
Traceback (most recent call last):
  File "C:\Users\user\Documents>DataStructures_Pt2.py", line 16, in <module>
    if wds[5] != 'random string' :
IndexError: list index out of range
Joseph
  • 1
  • 1
  • found out that the len(wds) was generating a value of 1 for the next line char – Joseph Feb 23 '23 at 18:25
  • The newline character would not be in `wds`, first because you already `rstrip`ped it away, and second because even if you hadn't, 0-argument `split` would discard leading and trailing whitespace. – user2357112 Feb 23 '23 at 18:29
  • You seem to be assuming that if `len(wds) >= 1`, then `len(wds) >= 6`. – chepner Feb 23 '23 at 18:29
  • Use `print(repr(line))` to see what your supposedly empty line actually contains. – chepner Feb 23 '23 at 18:30

1 Answers1

0

Found the problem - I was delimiting by the comma character so my text was not being delimited by whitespace. Which means the whitespace created a single character in the line making the len() = 1

I misunderstood and thought that the len() function automatically considered whitespace as nothing and therefore would return a 0. Lesson learned!

Joseph
  • 1
  • 1