Why Does The Csv Dictreader Dictionary Object Only Work While The File Is Still Open?
I'm been learning python and playing around with dictionaries and .csv files and the csv module. It seems like the csv.DictReader() function can help turn .csv files into dictionar
Solution 1:
csv.DictReader
doesn't read the entire file into memory when you create the cool_csv_dict
object. Each time you call it to get the next record from the CSV, it reads the next line from cool_csv_file
. Therefore, it needs this to be kept open so it can read from it as needed.
The argument to csv.DictReader
can be any iterator that returns lines. So if you don't want to keep the file open, you can call readlines()
to get all the lines into a list, then pass that to csv.DictReader
withopen("cool_csv.csv") as cool_csv_file:
cool_csv_lines = cool_csv_file.readlines()
cool_csv_dict = csv.DictReader(cool_csv_lines)
for row in cool_csv_dict:
print(row("Cool Fact")
Post a Comment for "Why Does The Csv Dictreader Dictionary Object Only Work While The File Is Still Open?"