【问题标题】:Python 3.6: How to save file with unicode/utf-8 filename? [closed]Python 3.6:如何使用 unicode/utf-8 文件名保存文件? [关闭]
【发布时间】:2017-11-17 14:31:13
【问题描述】:

所以我在编写 unicode 文件名的烧瓶中上传文件时遇到了麻烦。

这是我所拥有的:

   for name, file in request.files.items():

        if secure_filename(file.filename) in alternate_file_index: 

            path_to_save = "/test-unicode/B-286_10 - \u8907\u88fd.xls"

            # file.save(path_to_save) didnt work

            with open(path_to_save, "wb") as save_file:
                save_file.write(file.read())
        else:
            # English name files
            path_to_save = "path/to/save"
            file.save(path_to_save)

错误:

如果我使用 path_to_save.encode("utf-8"),我得到:

    fdst.write(buf)
AttributeError: 'bytes' object has no attribute 'write'

file.save(path_to_save) 给出这个错误:

 File "/flaskapp/env/lib/python3.6/site-packages/werkzeug/datastructures.py", line 2703, in save
    dst = open(dst, 'wb')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 54-55: ordinal not in range(128)

所有英文字符的情况都很好。

任何建议将不胜感激。泰。

回答: 在stackoverflow上发布这个问题后,这个bug已经神奇地解决了。

PS: path_to_save.encode("utf-8") 有效。显然,我错过了程序运行的那一刻。哈哈……

【问题讨论】:

  • 尝试添加.decode('utf-8')
  • path_to_save = path_to_save.decode('utf-8') AttributeError: 'str' object has no attribute 'decode'
  • 那是encode,不是decode
  • save_file.write(data.encode('utf-8'))。您正在尝试将 str 写入需要字节的文件对象。
  • 您的AttributeError 只是您的错误; fdst 是字节对象,而不是文件对象。您想改为拨打save_file.write(buf) 吗?

标签: python unicode flask


【解决方案1】:

添加参数“encoding = 'utf-8'”

  with open(path_to_save, "wb", encoding="utf-8") as save_file:
        save_file.write(data)

【讨论】:

  • 请阅读问题,它明确提到了 Python 3.6,不要不必要地投反对票
  • 已经是二进制模式了,这里就不传str了。因此编码没有任何意义。
  • 另外,发布的异常在没有隐式编码的 Python 3 中是 0 意义的,但是他们也有一个关于 bytes 没有属性的异常,这只能意味着 Python 3。
猜你喜欢
  • 2015-04-12
  • 1970-01-01
  • 2014-10-27
  • 2021-07-12
  • 2013-04-23
  • 1970-01-01
  • 2011-10-21
  • 2016-11-08
  • 1970-01-01
相关资源
最近更新 更多