How to read lines from a mmapped file?

前端 未结 4 1554
孤独总比滥情好
孤独总比滥情好 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:28

    The following is reasonably concise:

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

    Note that line retains the newline, so you might like to remove it. It is also the reason why if line == "" does the right thing (an empty line is returned as "\n").

    The reason the original iteration works the way it does is that mmap tries to look like both a file and a string. It looks like a string for the purposes of iteration.

    I have no idea why it can't (or chooses not to) provide readlines()/xreadlines().

提交回复
热议问题