user9764822
user9764822

Reputation:

Difference between csv.reader and .read when importing csv file

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()

Upvotes: 0

Views: 3494

Answers (1)

doctorlove
doctorlove

Reputation: 19232

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.

Upvotes: 1

Related Questions