通常读写文件使用read和write方法,都是以流的形式(一个字节接着一个字节)读写,假如需要针对某一位置读写,需要使用seek方法调整文件指针,但此方法对操作二进制文件是不方便的。
1、在访问二进制文件时,希望能把文件映射到内存中,可以像操作数组一样直接操作。Linux系统中的framebuffer设备文件。
2、某些嵌入式设备,寄存器被编址到内存地址空间,比如树霉派PWM波形寄存器,如要访问这个寄存器。
3、多进程映射同一个文件,可以实现进程通信。
>>> help(mmap.mmap) Help on class mmap in module mmap: class mmap(__builtin__.object) | Windows: mmap(fileno, length[, tagname[, access[, offset]]]) | | Maps length bytes from the file specified by the file handle fileno, | and returns a mmap object. If length is larger than the current size | of the file, the file is extended to contain length bytes. If length | is 0, the maximum length of the map is the current size of the file, | except that if the file is empty Windows raises an exception (you cannot | create an empty mapping on Windows). | | Unix: mmap(fileno, length[, flags[, prot[, access[, offset]]]]) | | Maps length bytes from the file specified by the file descriptor fileno, | and returns a mmap object. If length is 0, the maximum length of the map | will be the current size of the file when mmap is called. | flags specifies the nature of the mapping. MAP_PRIVATE creates a | private copy-on-write mapping, so changes to the contents of the mmap | object will be private to this process, and MAP_SHARED creates a mapping | that's shared with all other processes mapping the same areas of the file. | The default value is MAP_SHARED. | | To map anonymous memory, pass -1 as the fileno (both versions).
此函数针对window平台和linux平台使用方法和参数不同。第一个参数fileno是文件描述符而不是文件对象。
Python中的 open()打开一个文件,函数返回的是一个文件对象而不是文件描述符。
>>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.__doc__ for further information.
使用 os.open()打开一个文件返回的才是一个文件描述符。
>>> import os >>> help(os.open) Help on built-in function open in module nt: open(...) open(filename, flag [, mode=0777]) -> fd Open a file (for low level IO).
使用python的open()如何获得文件描述符,可以将得到的文件对象调用fileno()函数
>>> f = open(r'C:\视频\python高效实践技巧笔记\5文件IO操作相关话题\photo.jpg','r+b') >>> f.fileno() 4
>>> m = mmap.mmap(f.fileno(),0,access=mmap.ACCESS_WRITE) >>> type(m) <type 'mmap.mmap'>
access参数是代表权限,此时是写权限。第二个参数是映射长度,0就是整个文件的大小都映射。第一个参数是文件描述符。文件的类型和打开方式一致才能映射。
之后操作m就可以像数组一样操作
>>> m[0] '\xff' >>> m[10:20] '\n\t\x07\x0c\n\t\n\r\x0c\x0c' >>> m[0] = 0x88 Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> m[0] = 0x88 IndexError: mmap assignment must be single-character string
说明 不能对这个数组赋值数字,需要赋值字符串。
>>> m[0]= '\x88' >>> m[4:8] '\x00C\x00\x0c' >>> m[4] '\x00' >>> m[5] 'C' >>> m[6] '\x00' >>> m[7] '\x0c' >>> m[4:8] = '\xff'*4
显示时可显示字符时,直接显示字符,不能显示字符时显示转义
offset参数,偏移的单位不是字节而是页的整数倍,跳过几个页