You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python UnicodeEncodeError问题:urlopen结果含韩文写入文件失败

解决韩文写入文件的UnicodeEncodeError问题

嘿,这个问题我太熟悉了!你遇到的报错本质是文件打开时没有指定UTF-8编码导致的——Python默认会用系统自带的编码(Windows下通常是cp1252或者GBK这类),这些编码没法覆盖韩文这类Unicode字符,自然就编码失败了。

直接修改你的代码

只需要在open()函数里加上encoding="utf-8"参数就行,这样写入时就会用UTF-8编码保存,完美支持韩文:

from urllib.request import urlopen

openU = urlopen(myUrl)
pageH = openU.read()
openU.close()
stringU = pageH.decode("utf-8")
# 这里加上encoding="utf-8"指定编码
f = open("test.txt", "w+", encoding="utf-8")
f.write(stringU)
f.close()  # 别忘了手动关闭文件哦

更推荐的写法(用with语句自动管理资源)

with语句会自动帮你关闭文件和网络连接,避免忘记关闭资源的问题,代码更简洁安全:

from urllib.request import urlopen

# 自动管理网络连接
with urlopen(myUrl) as openU:
    pageH = openU.read()
    stringU = pageH.decode("utf-8")

# 自动管理文件,写完自动关闭
with open("test.txt", "w+", encoding="utf-8") as f:
    f.write(stringU)

这样修改后,韩文就能正常写入文件啦,你打开test.txt就能看到正确显示的所有字符了~

内容的提问来源于stack exchange,提问作者Chae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:13:51