在 python 中使用 mmap 函数需要的示例

发布于 2024-10-15 12:13:58 字数 98 浏览 4 评论 0原文

我正在寻找 python 中的示例来内存映射 1gb 文件。有人有我可以使用的例子吗?

该文件可以是任何随机文本。我只是想看看什么是正确的方法来做到这一点......

I am seeking an example in python to memory map a 1gb file. Does anyone have an example I can use?

The file can be any random text. I just want to look to see what is the proper way to do this...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼性发作 2024-10-22 12:13:58

这是一个可以帮助您理解 python (3.0+) 中的 mmap 的示例

下面的代码打开一个文件,然后对其进行内存映射。它执行映射文件的 readline() 方法,证明它的工作方式与标准文件一样。然后,它读取和写入映射文件的切片(访问映射文件内容的同等有效方法,不会更改文件指针)。最后,文件指针重新定位在开头,并读入(更新的)内容。(“14”是 write() 函数的返回值,它始终返回写入的字节数。)

>>> with open("myfile.txt", "wb") as f:
... f.write(b"Hello Python!\n")

>>> import mmap
>>> with open("myfile.txt", "r+b") as f:
... mapf = mmap.mmap(f.fileno(), 0)
... print(mapf.readline()) # prints b"Hello Python!\n"
... print(mapf[:5]) # prints b"Hello"
... mapf.tell()
... mapf[6:] = b" world!\n"
... mapf.seek(0)
... print(mapf.readline()) # prints b"Hello world!\n"
... mapf.close()
...
b'Hello Python!\n'
b'Hello'
14
b'Hello world!\n'

Here is an example that can help you understand mmap in python (3.0+)

The code below opens a file, then memory maps it. It exercises the readline() method of the mapped file, demonstrating that it works just as with a standard file. It then reads and writes slices of the mapped file (an equally valid way to access the mapped file's content, which does not alter the file pointer). Finally the file pointer is re-positioned at the start and the (updated) contents are read in. (The "14" is the return value of the write() function, which always returns the number of bytes written.)

>>> with open("myfile.txt", "wb") as f:
... f.write(b"Hello Python!\n")

>>> import mmap
>>> with open("myfile.txt", "r+b") as f:
... mapf = mmap.mmap(f.fileno(), 0)
... print(mapf.readline()) # prints b"Hello Python!\n"
... print(mapf[:5]) # prints b"Hello"
... mapf.tell()
... mapf[6:] = b" world!\n"
... mapf.seek(0)
... print(mapf.readline()) # prints b"Hello world!\n"
... mapf.close()
...
b'Hello Python!\n'
b'Hello'
14
b'Hello world!\n'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文