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

python2 和 python3 通过 mmap 读文件的区别

  •  
  •   sjmcefc2 · 2018-05-14 11:51:12 +08:00 · 1611 次点击
    这是一个创建于 2186 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 python2 下可以读出正确的 str 文字。

       with open(STAT_FILE, "r+b") as f:
            m=mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
            while True:
                   line=m.readline() 
                
                   if line == '': break
                   print line.rstrip()
    

    python3 下却只能读 bytes,用 f 也能正确读取字符串。 看了一些例子,貌似 python3 应该就是把文本当 str 的,为何有这个问题呢 怎样才能读出 string 呢。大部分行是 utf-8 编码,有部分行里个别字符不是 utf-8 编码。

     with open(STAT_FILE, "r+b") as f:
        m=mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
        while True:
                line=m.readline()
                line2 = f.readline()#读取字符串
                if line == '': break
                print ( line.rstrip())
    
    2 条回复    2018-05-15 23:30:38 +08:00
    luzhongqiu
        1
    luzhongqiu  
       2018-05-14 15:11:39 +08:00
    python3 中,utf8 编码就是 byte 类型,直接 decode 到 Unicode 编码好了。。。。。如果 decode 出错,尝试 errors='ignore'试试看
    sjmcefc2
        2
    sjmcefc2  
    OP
       2018-05-15 23:30:38 +08:00
    @luzhongqiu many thanks.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3390 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 736ms · UTC 13:11 · PVG 21:11 · LAX 06:11 · JFK 09:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.