Python 讀寫文件 中文亂碼 錯誤TypeError: write() argument must be str, not bytes+
阿新 • • 發佈:2017-11-10
with open handle hand 之前 med str 進制 pen set
今天寫上傳文件代碼,如下
def uploadHandle(request): pic1=request.FILES[‘pic1‘] picName=os.path.join(settings.MEDIA_ROOT,pic1.name) with open(picName,‘w‘) as pic: for c in pic1.chunks(): pic.write(c) return HttpResponse(picName)
出現TypeError: write() argument must be str, not bytes錯誤
網上搜索才發現原來是文件打開方式有問題,把之前的打開語句修改為用二進制方式打開就沒有問題
改為:
def uploadHandle(request): pic1=request.FILES[‘pic1‘] picName=os.path.join(settings.MEDIA_ROOT,pic1.name) with open(picName,‘wb+‘) as pic: for c in pic1.chunks(): pic.write(c) return HttpResponse(picName)
產生問題的原因是因為pickle存儲方式默認是二進制方式
Python 讀寫文件 中文亂碼 錯誤TypeError: write() argument must be str, not bytes+