简体   繁体   中英

Scope of variables using csv reader in Python

When I run this function on the file with 10 lines, it prints out the lines, but returns the length of 0. If I reverse the order, it prints out the length, but not the file content. I suppose this is a scope related issue, but not sure how to fix it

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        data = csv.reader(file)
        for row in data:
            print (row)
        lines = len ( list ( data ) )
        print(lines)

You are getting 0 because you have already looped over data.So now it is 0 .It is an iterator which is consumed.

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        data = csv.reader(file)
        x=0
        for row in data:
            x+=1
            print (row)
        lines = x
        print(lines)

The csv.reader() function returns an iterator (which are "consumed" when you use them) so you can only use data once. You can coerce convert it to a list before you do any operations on it to do what you want, eg data = list(data) .

The file reader remembers its place in the file like a bookmark

Printing each line and getting the length both move the bookmark all the way to the end of the file

Add data.seek(0) between the loop and getting the length. This moves the bookmark back to the start of the file

Try

def read_samples(name):
    with open ( '../data/samples/' + name + '.csv', encoding='utf-8', newline='') as file:
        my_list = []
        data = csv.reader(file)
        for row in data:
            print (row)
            my_list.append(row)
        lines = len (my_list)
        print(lines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM