2017-04-08 24 views
0

我已經寫在Django與上傳CSV文件一種形式簡單的應用程序。Django的,從形式請求讀取CSV拋出:錯誤:行包含空字節

我的CSV文件有很多列,其中有西裏爾字母。只是爲了測試我做了我的觀點處理HTML形式是這樣的:

@login_required() 
@require_http_methods(["POST"]) 
def upload_csv(request): 

    uploaded_file = request.FILES['csv'].read(200) 
    data = csv.reader(uploaded_file) 
    for row in data: 
     print(row) 

    return redirect('moderator:upload_view') 

當我嘗試上傳CSV我,我得到這個錯誤:

Traceback (most recent call last): 
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 149, in get_response 
response = self.process_exception_by_middleware(e, request) 
File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 147, in get_response 
response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "D:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view 
return view_func(request, *args, **kwargs) 
File "D:\Python27\lib\site-packages\django\views\decorators\http.py", line 42, in inner 
return func(request, *args, **kwargs) 
File "D:\myapp\moderator\views\upload.py", line 32, in upload_csv 
for row in data: 
Error: line contains NULL byte 
[08/Apr/2017 13:53:41] "POST /moderator/upload_csv/ HTTP/1.1" 500 87052 

首先,我認爲我的CSV已損壞。那麼爲什麼其他CSV閱讀器和Excel可以打開它?

回答

1

你可能想看看這個答案"Line contains NULL byte" in CSV reader (Python)

,它利用codecs library

import codecs 
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16')) 

打開與不同的編碼(如:UTF-16)的文件

好好運:)

+0

我已經是這樣的:'csvReader = csv.reader(codecs.open(uploaded_file,'儒的, 'utf-16'))'會拋出我'類型錯誤:文件()參數1必須編碼的字符串沒有空字節,不str' –

+0

在鏈接答案,存在的第二個最投票的答案,這給另一種解決方案(操作您的CSV)。你也可以嘗試一下! –

相關問題