简体   繁体   中英

Why does converting a csv_reader object to a list ouput an empty list?

I am trying to choose a random element from a csv file so I converted a csv_reader object to a list using the list() function but when I print it out, the list is empty. Why does this happen?

Code to replicate:

    with open('data.csv','r') as file:
        csvFile = csv.reader(file)
        row_count = sum(1 for row in csvFile)
        textToSend = list(csvFile)
        print(textToSend)
        #Outputs an empty list '[]'
  

You already read the entire file in sum(1 for row in csvFile) . There's nothng left to read when you do list(csvfile) .

You can rewind the file back to the beginning to read it again.

with open('data.csv','r') as file:
    csvFile = csv.reader(file)
    row_count = sum(1 for row in csvFile)
    file.seek(0)
    textToSend = list(csvFile)
    print(textToSend)

Or you can read everything into a list first.

with open('data.csv','r') as file:
    csvFile = list(csv.reader(file))
    row_count = len(csvFile)
    textToSend = csvFile
    print(textToSend)

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