Error- local variable referenced before assignment

Question:

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
Asked By: dreamkeeper

||

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()
Answered By: Roy

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()
Answered By: NotDavid

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
Answered By: xaleel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.