我在关闭的文件上遇到了一个' I / O操作'在csv_reader中循环每一行时的问题。
这是我的代码:
logFile = request.FILES['logs']
array = []
with logFile as csv_file:
field_names = ['hi', 'hi', 'hello', 'hello' ]
delimiter = ','
quote_character = '"'
csv_reader = csv.DictReader(csv_file, fieldnames=field_names , delimiter = delimiter, quotechar = quote_character)
count = 0
for rows in csv_reader:
if count == 0:
print count
else:
print count
array.append(rows)
count += 1
return array
logFile是用户上传的实际csv文件,而不是路径。
Traceback:
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vcap/app/BillingWebApp/views.py" in IndexView
128. csv_list_dict = csv_getting_list_dict.Csv_Parser(logFile)
File "/home/vcap/app/BillingWebApp/csv_getting_list_dict.py" in Csv_Parser
5. with logFile.open() as csv_file:
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/uploadedfile.py" in open
97. self.file.seek(0)
Exception Type: ValueError at /
Exception Value: I/O operation on closed file.
我的代码中出现错误:
for rows in csv_reader:
并在调试器中得到:
row = self.reader.next()
答案 0 :(得分:0)
LogFile
的类型是:
<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
对于with logFile as csv_file:
语句,您需要文件对象,即<type 'file'>
。
您需要将LogFile
保存到文件中,然后再次打开文件以进行下一个过程。
答案 1 :(得分:0)
此方法假设您的csv文件可以加载到内存中:
from cStringIO import StringIO
log_file = request.FILES['logs']
log_file.seek(0)
log_file_content = log_file.read()
in_memory_log_file = StringIO(log_file_content)
array = []
field_names = ['hi', 'hi', 'hello', 'hello' ]
delimiter = ','
quote_character = '"'
csv_reader = csv.DictReader(in_memory_log_file, fieldnames=field_names ,
delimiter = delimiter, quotechar = quote_character)
count = 0
for row in csv_reader:
if count == 0:
print count
else:
print count
array.append(row)
count += 1
return array
答案 2 :(得分:0)
首先阅读文件。您可能想尝试这样的事情:
data = [row for row in csv.DictReader(csv_file.read(), fieldnames=field_names,
delimiter=delimiter, quotechar=quote_character)]