【发布时间】:2019-11-27 19:36:17
【问题描述】:
我们正在尝试使用 pythonanywhere.com 主机中的 view.py 读取 csv 文件。 我们希望从 1.csv 文件的每一行中获取三个单元格(id、语句和段落),直到最后一个。
代码是:
def home(request):
Stats = Statments.objects.all()
__file__ = '1.csv'
module_dir = os.path.dirname(__file__) # get current directory
file_name = os.path.join(module_dir, 'Politi_Stat/1.csv')
#Load statments to database from CSV
with open(file_name,"r", encoding = 'utf-8') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
book = Statments(id = row[0] ,statment=row[1], Paragraph=row[2])
book.save()
d = deque(posts)
d.extendleft(reversed(Stats))
我们导入 csv 和 os。好像是csv的unicode UTF-8的编码问题。
网站的输出是: 服务器 500
日志文件的输出是:
Traceback (most recent call last):
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home
for row in csv_reader:
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 82: invalid start byte
2019-11-27 19:20:54,714: Internal Server Error: /
Traceback (most recent call last):
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home
for row in csv_reader:
File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
【问题讨论】:
-
csv 文件不是 UTF-8 编码的。它是在 Windows 机器上创建的吗?
-
在 Mac OS 上创建。但我现在使用的是 Windows。
-
如果 csv 文件不是 utf-8 编码,那么您的代码将无法工作
-
好的,感谢您的通知。
标签: python django csv encoding utf-8