Python 读写文件 中文乱码 错误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,'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存储方式默认是二进制方式

上一篇:Bootstrap入门(十八)组件12:徽章与巨幕


下一篇:mvc中测试网络