Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+

时间:2021-06-05 21:25:14

今天写上传文件代码,如下

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存储方式默认是二进制方式