0

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 '[]'
  

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.