Python随机访问文件 [英] Python Random Access File

查看:96
本文介绍了Python随机访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个Python文件类型访问随机行而不遍历整个文件?我需要在一个大文件中搜索,将整个内容读入内存是不可能的。



任何类型或方法将不胜感激。 $ b

解决方案

这似乎只是这样的事情 mmap 是专为。 mmap 对象创建一个类似于字符串的文件接口:

  >>> f = open(bonnie.txt,wb)
>>> f.write(我的邦妮躺在海洋上)
>>> f.close()
>>> (bonnie.txt,r + b)
>>> mm = mmap(f.fileno(),0)
>>>打印mm [3:9]
Bonnie

如果您想知道 mmap 对象也可以分配给:

 >>>打印mm [24:] 
海洋。
>>> mm [24:] =海。
>>>打印mm [:]
我的邦妮躺在海面上。


Is there a Python file type for accessing random lines without traversing the whole file? I need to search within a large file, reading the whole thing into memory wouldn't be possible.

Any types or methods would be appreciated.

解决方案

This seems like just the sort of thing mmap was designed for. A mmap object creates a string-like interface to a file:

>>> f = open("bonnie.txt", "wb")
>>> f.write("My Bonnie lies over the ocean.")
>>> f.close()
>>> f.open("bonnie.txt", "r+b")
>>> mm = mmap(f.fileno(), 0)
>>> print mm[3:9]
Bonnie

In case you were wondering, mmap objects can also be assigned to:

>>> print mm[24:]
ocean.
>>> mm[24:] = "sea.  "
>>> print mm[:]
My Bonnie lies over the sea.  

这篇关于Python随机访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆