How to read lines from a mmapped file?

前端 未结 4 1561
孤独总比滥情好
孤独总比滥情好 2020-12-24 02:48

Is seems that the mmap interface only supports readline(). If I try to iterate over the object I get character instead of complete lines.

What would be the \"python

4条回答
  •  情歌与酒
    2020-12-24 03:10

    The most concise way to iterate over the lines of an mmap is

    with open(STAT_FILE, "r+b") as f:
        map_file = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
        for line in iter(map_file.readline, b""):
            # whatever
    

    Note that in Python 3 the sentinel parameter of iter() must be of type bytes, while in Python 2 it needs to be a str (i.e. "" instead of b"").

提交回复
热议问题