differences between output of printing contents of file directly vs using using the csv.reader() in python?

Viewed 26

i am working with a csv file in python and just discovered that after i open it like this : with open("randomfile.csv", "r") as csvfile, i can read contents in two ways :

#1
Content1 = next(csvfile)`
#2 
csvreader = csv.reader(csvfile)
Content2 = next(csvreader)

but the type of Content1 is a string whereas the type of Content2 is a list, anyone knows why ?

EDIT : Turns out if you write

csvreader = csv.reader(csvfile)

Then writing

Content1 = next(csvfile)

will now output a list too

1 Answers

Hi csvreader is a special library to help you make it easier to work with csv files, as well as tab-separated files (tsv) and similar types of common delimited files.

In this case using next(csvfile) you are just reading the next line by calling next on the file (let's say - this is the "ordinary python" way of reading a file). When you do this you get the next line as a string. This is exactly what happens if you use a for loop

for line in open('randomfile.csv'):
    print(line)

But when you call next on the csvreader the csv package is "helping" you by splitting the line into a list. You'll also notice that you don't have to think so much about end of line characters (\n) either! So it basically is trying to assist you to work with the file more easily. Doing this kind of splitting and turning the line into a list of fields can done and isn't super hard but all kind of other things can happen with csv files (like surrounding the fields with double quotes, and handling commas inside files. The csv package helps with all of these things as well: https://docs.python.org/3/library/csv.html

Related