推荐学习书目
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 · Dec 20, 2018 · 3311 views
    This topic created in 2734 days ago, the information mentioned may be changed or developed.
    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 replies    2018-12-20 08:52:43 +08:00
    wevsty
        1
    wevsty  
       Dec 20, 2018   ❤️ 1
    代码里面 encoding 不是 utf-8 么?和 gb18030 的关系是?
    你用个能用 UTF-8 编码打开文件的文本编辑器应该就正常了。
    guog
        2
    guog  
       Dec 20, 2018 via Android   ❤️ 1
    换 Python3 试试?
    Vegetable
        3
    Vegetable  
       Dec 20, 2018 via Android   ❤️ 1
    @guog open 有 encoding 参数就是 py3 了
    Sylv
        4
    Sylv  
       Dec 20, 2018   ❤️ 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  
       Dec 20, 2018   ❤️ 2
    如果乱码是指用 excel 打开看到话应该是楼上说的原因.
    或者用 excel 的导入功能, 可以正常打开 utf8 格式的 csv
    king1101
        6
    king1101  
    OP
       Dec 20, 2018
    @guog 一直使用的都是 py3,对于 py2 了解有限,不过你楼下已经给出了解答,还是谢谢
    king1101
        7
    king1101  
    OP
       Dec 20, 2018
    @Sylv 感谢,已测可行
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5896 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 06:15 · PVG 14:15 · LAX 23:15 · JFK 02:15
    ♥ Do have faith in what you're doing.