似乎mmap接口仅支持readline()。如果我尝试遍历对象,则会得到字符而不是完整的行。
逐行读取mmap文件的“ pythonic”方法是什么?
import sys import mmap import os if (len(sys.argv) > 1): STAT_FILE=sys.argv[1] print STAT_FILE else: print "Need to know <statistics file name path>" sys.exit(1) with open(STAT_FILE, "r") as f: map = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) for line in map: print line # RETURNS single characters instead of whole line
遍历an行的最简洁方法mmap是
mmap
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
请注意,在Python 3的前哨参数iter()必须是类型的bytes,而在Python 2它需要一个str(即"",而不是b"")。
iter()
bytes
str
""
b""