V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
2736
V2EX  ›  Python

萌新提问: UnicodeEncodeError 错误,可以正常显示字符但写入文件失败

  •  
  •   2736 · 2018-05-29 17:15:17 +08:00 · 1644 次点击
    这是一个创建于 2152 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我在用 python 下载某个网页里的资料,获取的某一个 str 里面有些字符能正常 print 但是无法写入文件里,报错。 UnicodeEncodeError: 'gbk' codec can't encode character '\xf6' in position 308: illegal multibyte sequence 不知道应该如何解决? 写代码检查这个错误时,代码是这样的:
    c = open('a2','w')
    print('\xf6')
    c.write('\xf6')
    c.close()
    源文件局部是这样的:
    import urllib.request
    from bs4 import BeautifulSoup
    c = open('c1','w')
    d = urllib.request.urlopen('http://www.efloras.org/florataxon.aspx?flora_id=3&taxon_id=200012756')
    e = BeautifulSoup(d.read().decode(encoding="utf-8"),"lxml")
    c.write(e.find(attrs={'id': 'lblTaxonDesc'}).get_text())
    if e.find(attrs={'title': 'Illustration'}):
    c.write(str(e.find(attrs={'title': 'Illustration'})))
    c.close()

    代码里的倒数第二行的 Tab 打不出来。

    5 条回复    2018-05-29 18:44:26 +08:00
    awli
        1
    awli  
       2018-05-29 17:38:25 +08:00
    看了你的代码我有种蛋蛋疼的感觉 ignore 可以不?
    zynlp
        2
    zynlp  
       2018-05-29 17:56:06 +08:00 via iPhone
    open 里加个 encoding=“ utf8 ”,或者直接 error=“ ignore ”
    你这估计是 windows 下默认 gbk 打开文件,‘\xf6 ’不在 gbk 编码表里,写不进去的
    zwzmzd
        3
    zwzmzd  
       2018-05-29 18:17:53 +08:00 via iPhone
    运行前设置一下这个环境变量
    PYTHONIOENCODING=UTF-8
    2736
        4
    2736  
    OP
       2018-05-29 18:43:18 +08:00
    我不是程序员啊,写代码只是为了临时解决某个问题的,这些代码只要调试完没问题,收集完数据了就不再使用了。
    我之前想过可以用 ignore,但不知道往哪里插。
    2736
        5
    2736  
    OP
       2018-05-29 18:44:26 +08:00
    open 里加上 encoding=“ utf8 ”解决了问题,非常感谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4059 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:14 · PVG 18:14 · LAX 03:14 · JFK 06:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.