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

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

问题描述

是否有一种 Python 文件类型可以在不遍历整个文件的情况下访问随机行?我需要在一个大文件中进行搜索,不可能将整个文件读入内存.

任何类型或方法将不胜感激.

解决方案

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

<预><代码>>>>f = open("bonnie.txt", "wb")>>>f.write("我的邦妮躺在海上.")>>>f.close()>>>f.open("bonnie.txt", "r+b")>>>mm = mmap(f.fileno(), 0)>>>打印毫米[3:9]邦妮

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

<预><代码>>>>打印毫米 [24:]海洋.>>>mm[24:] = "海.">>>打印毫米[:]我的邦妮躺在海上.

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天全站免登陆