-2

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
Turan
  • 104
  • 9
  • 4
    Put `rows = 0` inside the function. – Daniil Fajnberg Sep 08 '22 at 10:09
  • Welcome to Stack Overflow. Please read [ask], and [please try](https://meta.stackoverflow.com/questions/261592) to research questions before asking. For example, what happens if you try [copying and pasting the interesting part of the error message into a search engine](https://duckduckgo.com/?q=local+variable+referenced+before+assignment)? – Karl Knechtel Sep 08 '22 at 10:10
  • It depends if you want *rows* to be local or global. If the former then move *rows = 0* inside the function. If the latter add *global rows* inside the function – DarkKnight Sep 08 '22 at 10:11

3 Answers3

0

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()
Roy
  • 398
  • 2
  • 12
0

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()
NotDavid
  • 161
  • 7
0

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
xaleel
  • 173
  • 5
  • 1
    That's good to know. Still learning and so many ways to do something. I'm taking the long winded route currently. – dreamkeeper Sep 08 '22 at 10:23