Reputation: 27
For a CSV file:
While the code below works fine to output the rows of the CSV:
import csv
import sys
database = {}
with open(sys.argv[1], mode='r') as csv_file:
database = csv.DictReader(csv_file)
for row in database:
print(row)
the following does not.
import csv
import sys
database = {}
with open(sys.argv[1], mode='r') as csv_file:
database = csv.DictReader(csv_file)
for row in database:
print(row)
with error
> Traceback (most recent call last): File "test.py", line 9, in
> <module>
> for row in database: File "/usr/local/lib/python3.7/csv.py", line 111, in __next__
> self.fieldnames File "/usr/local/lib/python3.7/csv.py", line 98, in fieldnames
> self._fieldnames = next(self.reader) ValueError: I/O operation on closed file.
The csv.DictReader object appears to exist but I cannot iterate over it in the 2nd snippet. Checking various comments, they seem to say that DictReader returns an iterator - but I do not know understand if this is the reason for the error and what to change to gain access to database. Appreciate any help. Thanks in advance!
Upvotes: 0
Views: 2135
Reputation: 153
While getting csv file in API (Django) you can do something like this
import csv
import io
csv_file = request.FILES.get('csv_file')
file = csv_file.read().decode('utf-8')
csv_reader = csv.DictReader(io.StringIO(file))
for row in csv_reader:
print(row)
Upvotes: 0
Reputation: 356
with open
is a context manager which closes the file when execution goes out of scope. As the file is closed you can't read from it.
Use the original indentation.
import csv
import sys
database = {}
with open(sys.argv[1], mode='r') as csv_file:
database = csv.DictReader(csv_file)
for row in database:
print(row)
You could also do the following:
import csv
import sys
with open(sys.argv[1], mode='r') as csv_file:
rows = list(csv.DictReader(csv_file))
for row in rows:
print(row)
The second way will pull all the data into memory.
Upvotes: 1