免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2295 | 回复: 6
打印 上一主题 下一主题

文件内容和列表的映射模块 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-08-21 09:26 |只看该作者 |倒序浏览
我想问下,Python里有没有提供这样一个模块:

1. 能把文件按照数据行映射到一个数组里去。(这个原生的Python可行)。
2. 对这个数组的修改,能够自动到更新到文件里去,而无需显示的用写的方法来同步。
3. 应该不是mmap这个模块

论坛徽章:
0
2 [报告]
发表于 2012-08-21 09:33 |只看该作者
回复 1# zhuyubei
不用mmap怎么实现?


   

论坛徽章:
0
3 [报告]
发表于 2012-08-21 09:49 |只看该作者
mmap是字节形式的映射。当然对它进行包装是可以实现这样的功能的。也就是说,没有直接提供这样的包是吗。

论坛徽章:
0
4 [报告]
发表于 2012-08-21 10:33 |只看该作者
回复 1# zhuyubei
没明白你的需求,感觉没啥要包装的。
  1. with open("d:/hello.txt", "wb") as f:
  2.     f.write("Hello Python!\n")
  3. with open("d:/hello.txt", "r+b") as f:
  4.     map = mmap.mmap(f.fileno(), 0)
  5.     print map.readline()
  6.     print map[:5]
  7.     map[6:] = "\nworld!\n"
  8.     map.seek(0)
  9.     print map.readline()  
  10.     print map.readline()
  11.     map.close()
  12.    
复制代码

论坛徽章:
0
5 [报告]
发表于 2012-08-21 10:52 |只看该作者
回复 4# 106033177


    谢谢您的回复。我再好好把mmap的文档看下。谢谢!

论坛徽章:
4
水瓶座
日期:2013-09-06 12:27:30摩羯座
日期:2013-09-28 14:07:46处女座
日期:2013-10-24 14:25:01酉鸡
日期:2014-04-07 11:54:15
6 [报告]
发表于 2012-08-21 12:53 |只看该作者
  1. import mmap

  2. # write a simple example file
  3. with open("hello.txt", "wb") as f:
  4.     f.write(b"Hello Python!\n")

  5. with open("hello.txt", "r+b") as f:
  6.     # memory-map the file, size 0 means whole file
  7.     map = mmap.mmap(f.fileno(), 0)
  8.     # read content via standard file methods
  9.     print(map.readline())  # prints b"Hello Python!\n"
  10.     # read content via slice notation
  11.     print(map[:5])  # prints b"Hello"
  12.     # update content using slice notation;
  13.     # note that new content must have same size
  14.     map[6:] = b" world!\n"
  15.     # ... and read again using standard file methods
  16.     map.seek(0)
  17.     print(map.readline())  # prints b"Hello  world!\n"
  18.     # close the map
  19.     map.close()
复制代码

论坛徽章:
2
CU大牛徽章
日期:2013-04-17 11:46:28CU大牛徽章
日期:2013-04-17 11:46:39
7 [报告]
发表于 2012-08-22 23:56 |只看该作者
不能用 pickle、shelve 么?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP