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
king1101
V2EX  ›  Python

一个编码问题。。。

  •  
  •   king1101 · 2018-12-20 00:05:41 +08:00 · 2367 次点击
    这是一个创建于 1926 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import csv
    
    with open("demo.csv","w",encoding= "utf-8") as f:
    	w = csv.writer(f)
    	w.writerow(u'\u22ef')
    

    结果写进 csv 的是乱码,采用 gb18030 编码写进 csv 的是"??",如果不添加 encoding 就会报 gbk 错误

    如果单纯只是print(u'\u22ef'),结果是“……”,请问如何才能将省略号写入 csv。

    谢谢!

    7 条回复    2018-12-20 08:52:43 +08:00
    wevsty
        1
    wevsty  
       2018-12-20 00:30:31 +08:00   ❤️ 1
    代码里面 encoding 不是 utf-8 么?和 gb18030 的关系是?
    你用个能用 UTF-8 编码打开文件的文本编辑器应该就正常了。
    guog
        2
    guog  
       2018-12-20 01:03:27 +08:00 via Android   ❤️ 1
    换 Python3 试试?
    Vegetable
        3
    Vegetable  
       2018-12-20 01:10:32 +08:00 via Android   ❤️ 1
    @guog open 有 encoding 参数就是 py3 了
    Sylv
        4
    Sylv  
       2018-12-20 02:38:47 +08:00   ❤️ 3
    UTF-8 编码的 csv 文件需要加 BOM 头,Excel 才能正确识别:

    import csv
    import codecs

    with open("demo.csv","wb") as f:
    -> f.write(codecs.BOM_UTF8)

    with open("demo.csv","a",encoding="utf-8") as f:
    -> w = csv.writer(f)
    -> w.writerow(u'\u22ef')
    Trim21
        5
    Trim21  
       2018-12-20 05:08:03 +08:00   ❤️ 2
    如果乱码是指用 excel 打开看到话应该是楼上说的原因.
    或者用 excel 的导入功能, 可以正常打开 utf8 格式的 csv
    king1101
        6
    king1101  
    OP
       2018-12-20 08:50:44 +08:00
    @guog 一直使用的都是 py3,对于 py2 了解有限,不过你楼下已经给出了解答,还是谢谢
    king1101
        7
    king1101  
    OP
       2018-12-20 08:52:43 +08:00
    @Sylv 感谢,已测可行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1448 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 23:49 · PVG 07:49 · LAX 16:49 · JFK 19:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.