Error- local variable referenced before assignment

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

>Solution :

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()

Leave a Reply