Error- local variable referenced before assignment

Viewed 32

What I'm sure is another simple error, but I'm going around in circles. I'm trying to get it to show the first 10 lines in a csv using a function. I can get 1 line to show before it throws an error. Maybe my rows=0 needs to be moved down further, but I'm not sure and my attempts at moving it hasn't worked?


rows = 0

def lines():
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()
UnboundLocalError                         Traceback (most recent call last)
Input In [57], in <cell line: 14>()
     11             if(rows>=5):
     12                 break
---> 14 lines()

Input In [57], in lines()
      8 for row in dictreader:
      9     print(row)
---> 10     rows=rows+1
     11     if(rows>=5):
     12         break

UnboundLocalError: local variable 'rows' referenced before assignment
3 Answers

This should work:

def lines():
    rows = 0
    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

Your rows is outside the function so the lines function cannot access the variable. Try moving rows inside the lines function like this.

def lines():
    rows = 0

    with open('iamacsvfile.csv') as file:
        dictreader = csv.DictReader(file)
        for row in dictreader:
            print(row)
            rows=rows+1
            if(rows>=10):
                break

lines()

You haven't defined rows.

But you don't need that, since csv.DictReader has line_num property, which increases with each iteration. It's better to use:

for row in dictreader:
    print(row)
    if dictreader.line_num >= 10:
        break
Related