0

What is the point of

with open('grades.csv', 'r') as csvfile

in this code ????

import csv

with open('grades.csv', 'r') as csvfile:
    grades_reader = csv.reader(csvfile, delimiter=',')

    row_num = 1
    for row in grades_reader:
        print('Row #{}:'.format(row_num), row)
        row_num += 1

?? becuase when I rewrite the code again as:

import csv
grades_reader=open('grades.csv', 'r')
row_num = 1
for row in grades_reader:
    print('Row #{}:'.format(row_num), row)
    row_num += 1

I get the same result but without the output being a list. So is it safe to assume that with command will turn it to a list when read?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Jack
  • 725
  • 1
  • 10
  • 27
  • You should prefer to use with() as that'll close the file and prevent resource leaks, but as answered, that's not the root cause here – OneCricketeer May 05 '21 at 05:02

1 Answers1

0

It's not about with open('grades.csv', 'r') as csvfile: line.
It's about grades_reader = csv.reader(csvfile, delimiter=',') in the first case.

In the first case, you are using the csv.reader, so it returns a list.
In the second case, you're just reading the file as text.

You can change the second case as, to get the same result as the first case

import csv
grades_reader=open('grades.csv', 'r')
grades_reader = csv.reader(grades_reader, delimiter=',')
row_num = 1
for row in grades_reader:
    print('Row #{}:'.format(row_num), row)
    row_num += 1

Here are few discussions that you can find that talks about python's with statement
What is the python "with" statement designed for?
What is the python keyword "with" used for?

imdevskp
  • 2,103
  • 2
  • 9
  • 23