Python 写文件报错TypeError的解决办法

处理上传的文件:
        f1 = request.FILES['pic']
        fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name)
        with open(fname, 'w') as pic:
            for c in f1.chunks():
                pic.write(c)


测试报错:
TypeError at /upload/   
write() argument must be str, not bytes


把之前的打开语句修改为用二进制方式打开:


        f1 = request.FILES['pic']
        fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name)
        with open(fname, 'wb+') as pic:
            for c in f1.chunks():
                pic.write(c)

没有问题了


你可能感兴趣的:(Django)