0

What is the difference in importing csv file with reader and with .read

import csv
f = open("nfl.csv", 'r')
data = csv.reader(f)

and using read directly

f = open('nfl.csv', 'r')
data = f.read()
1
  • f.read() just reads a file and has no concept of CSV. data = csv.reader(f) assigns the reader object to the name data, but does not consume it, compared to for example data = list(csv.reader(f)). Commented May 22, 2018 at 11:52

1 Answer 1

1

From the docs, the reader will

Return a reader object which will iterate over lines in the given csvfile.

whereas the read on a file, will

reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory.

So, the first way, you can use

for row in reader: 

and processes the lines one at a time. You can also do things one line at a time for a file in general.

The csv module expects comma seprated columns though, so you get a list or a dictionary of the data depending on how you set things up.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you ! Atleast I know I must look in the documents first :)

Your Answer

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