Python 特殊字符未保留在写入“wb”的文件中

问题描述 投票:0回答:1

我在以下功能中遇到问题:

def download_zip(key: str):
    response = requests.get('some url')

    if response.status_code == 200:
        header = response.headers.get('content-disposition')

        if type(header) == str:
            file_name = re.findall("filename=(.+)", header)[0][1:-1]
        else:
            file_name = f"{key}.zip"

        with open(file_name, mode='wb') as f:
            f.write(response.content)

        print(f"Written: {file_name}")

    else:
        print(f"Failed: {key} -> {response.status_code}")


URL“some url”指向一个 zip 文件。

使用浏览器下载文件时,其名称中包含日语字符,这些字符被保留:

音のないレプリカ
。 在我的代码中,它们不是这样,而是生成如下所示的内容:
é³ã®ãªãã¬ããªã«
。我怎样才能让它保留这些字符?

python python-3.x file character-encoding zip
1个回答
0
投票

特定情况的解决方案:将编码修复为(您认为的)应该是的:

file_name.encode('iso-8859-1').decode('utf-8')

更通用的解决方案:向网络服务器的所有者大喊以修复其标头,然后正确设置

filename*
Content-Disposition
字段。然后您就可以对正确的编码有一定的信心。

© www.soinside.com 2019 - 2024. All rights reserved.