博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python标准库介绍——19 mmap 模块详解
阅读量:7112 次
发布时间:2019-06-28

本文共 1352 字,大约阅读时间需要 4 分钟。

==mmap 模块==(2.0 新增) ``mmap`` 模块提供了操作系统内存映射函数的接口, 如 [Example 2-13 #eg-2-13] 所示. 映射区域的行为和字符串对象类似, 但数据是直接从文件读取的.====Example 2-13. 使用 mmap 模块====[eg-2-13]```File: mmap-example-1.pyimport mmapimport osfilename = "samples/sample.txt"file = open(filename, "r+")size = os.path.getsize(filename)data = mmap.mmap(file.fileno(), size)# basicsprint dataprint len(data), size# use slicing to read from the file# 使用切片操作读取文件print repr(data[:10]), repr(data[:10])# or use the standard file interface# 或使用标准的文件接口print repr(data.read(10)), repr(data.read(10))*B*
302 302'We will pe' 'We will pe''We will pe' 'rhaps even'*b*```在 Windows 下, 这个文件必须以既可读又可写的模式打开( `r+` , `w+` , 或 `a+` ), 否则 ``mmap`` 调用会失败. ``` [!Feather 注: 经本人测试, a+ 模式是完全可以的, 原文只有 r+ 和 w+]%% WindowsError: [Error 5] Access is denied 一般是这个错误 [Example 2-14 #eg-2-14] 展示了内存映射区域的使用, 在很多地方它都可以替换普通字符串使用, 包括正则表达式和其他字符串操作.====Example 2-14. 对映射区域使用字符串方法和正则表达式====[eg-2-14]```File: mmap-example-2.pyimport mmapimport os, string, redef mapfile(filename): file = open(filename, "r+") size = os.path.getsize(filename) return mmap.mmap(file.fileno(), size)data = mapfile("samples/sample.txt")# searchindex = data.find("small")print index, repr(data[index-5:index+15])# regular expressions work too!m = re.search("small", data)print m.start(), m.group()*B*43 'only small\015\012modules '43 small*b*```

 

转载地址:http://lxghl.baihongyu.com/

你可能感兴趣的文章
jvm类加载机制
查看>>
让更多人知道你——给开源库提交 pr
查看>>
使用ipmi调节r410的风扇转速
查看>>
Spring Cloud超简单十分钟入门实例
查看>>
Linux环境Apache2.4+mysql5.7+php5.6快速安装mysql
查看>>
MySql 日常指导,及大表优化思路
查看>>
设计模式之 - 单例模式
查看>>
用 Python 脚本,监听附近网络 Wi-Fi 设备,通过邮件和微信进行消息推送
查看>>
巅峰之证!首位阿里云ACE认证专家产生
查看>>
Spring Cloud Alibaba Sentinel对RestTemplate的支持
查看>>
canvas
查看>>
2018-07-30 到 2018-08-03
查看>>
昨天,我们公司的产品经理被我...
查看>>
【今日头条】【抖音火山】后台开发实习生
查看>>
js文件操作总结一:图片篇
查看>>
外观模式
查看>>
javascript之函数防抖与节流
查看>>
docker 部署前端
查看>>
Spring定时任务的几种实现
查看>>
web前端程序员真的值这么多钱吗?
查看>>