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

codecs模块中以utf-8编码open文件,读取时丢失信息

  •  
  •   KotiyaSanae ·
    SeavantUUz · 2013-06-23 12:13:45 +08:00 · 4158 次点击
    这是一个创建于 3931 天前的主题,其中的信息可能已经有所发展或是发生改变。
    问题描述如标题,这里追加一点是:读取时如果混用read和readline或者read和next的话,就会出现丢失的问题。
    问题重现:
    讨论1
    import codecs
    f = codecs.open('example','r','utf-8')
    print f.readline()
    print f.read()
    说明:example是一个至少一行的文件,建议大于5行,有必要的话,我可以提供本地的那份。
    上面的代码,应该是先打印出一行,然后再打印剩下的内容---原本的想法。事实上,f.read()那部分打印不完全。

    讨论2
    import codecs
    f = codecs.open('example','r')
    print f.readline()
    print f.read()
    上面的代码没有译码的那个参数,然后运行没问题。

    讨论三
    import codecs
    f = codecs.open('example','r')
    print f.next()
    print f.read()
    这个会上抛一个异常:ValueError: Mixing iteration and read methods would lose data,我感觉能理解。

    讨论四:
    import codecs
    f = codecs.open('example','r','utf-8')
    print f.next()
    print f.read()
    吊诡的来了,联系讨论三,这个应该会上抛异常,但是实际上,这个行为和讨论一一模一样……
    综上,我觉得codecs模块不太严谨,有些行为值得商榷,或者是我的问题?
    最后,求高人指点,如何能优雅地分割一个文件,具体的,我需要前四行每行分析一次,然后剩下的文本直接合在一起。虽然readlines应该没问题,但是感觉有点不雅观,生成器不熟,没法写得很花俏,于是应该怎么做呢?
    Thanks
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1378 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:39 · PVG 07:39 · LAX 16:39 · JFK 19:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.