情况:我有一个使用 mmap 加载到 RAM 中的 CVD(ClamAV 病毒数据库)文件。CVD 文件中每一行的格式与 CSV 文件之一相同(以“:”分隔)。下面是代码的一个片段:
def mapping():
with open("main.cvd", 'rt') as f:
global mapper
mapper = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)
def compare(hashed):
for row in csv.reader(mapper, dialect='delimit'):
if row[1] == hashed:
print('Found!')
问题:运行时,返回错误 _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
问题:如何将 CSV 文件作为已加载到内存中的文本读取?
附加信息 1:我试过使用StringIO
,它抛出错误TypeError: initial_value must be str or None, not mmap.mmap
附加信息 2:我需要将文件放在 RAM 中以便更快地访问文件,并且我不能牺牲时间使用诸如 readline()
构造函数的csvfile
参数csv.reader
“可以是任何支持迭代器协议并在每次next()
调用其方法时返回一个字符串的对象”。
这意味着“对象”可以是生成器函数或生成器表达式。在下面的代码中,我实现了一个生成器函数mmap_file_reader()
,该函数将内存映射中的字节转换为字符串以及yield
它检测到的每一行输出。
我将mmap.mmap
构造函数调用设置为有条件的,因此它也可以在 Windows 上运行。如果您使用access=
关键字而不是prot=
关键字,这应该是不必要的——但我无法测试,所以按所示进行了测试。
import csv
import mmap
import sys
def mapping():
with open("main.cvd", 'rt') as f:
global mapper
if sys.platform.startswith('win32'):
mmf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) # windows
else:
mmf = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) # unix
mapper = mmap_file_reader(mmf)
csv.register_dialect('delimit', delimiter=':', quoting=csv.QUOTE_NONE)
def mmap_file_reader(mmf):
'''Yield successive lines of the given memory-mapped file as strings.
Generator function which reads and converts the bytes of the given mmapped file
to strings and yields them one line at a time.
'''
while True:
line = mmf.readline()
if not line: # EOF?
return
yield str(line, encoding='utf-8') # convert bytes of lineread into a string
def compare(hashed):
for row in csv.reader(mapper, dialect='delimit'):
if row[1] == hashed:
print('Found!')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句