Why does the DictReader Dictionary object only work while the file is still open?
Since we saved it to a python variable, shouldn’t we be able to call the variable after we close the file, like when using read() in the previous exercises?
I know the proper way to code this would be:
with open("cool_csv.csv") as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row["Cool Fact"])
But why does the for row in cool_csv_dict: section have to be nested in the open() section?
I don’t intuitively understand why the following code returns a ValueError: I/O operation on closed file.
with open("cool_csv.csv") as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row["Cool Fact"])
My only guess would be that because the csv.DictReader object is not quite an actual dictionary (or something), there’s some shenanigans because it still needs to point somewhere. Can anyone shed any light?
Codeacademy, I request please explain things properly, don’t jump, I didn’t get why the newline=“” argument was passed in open() function along with the csv file. Before that I just thought that only w,a, and r can be passed, please explain first what arguments can be passed in open() function, then move ahead, it will be easy.