【发布时间】: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)吗?