2007-07-10

 

Python Cookbook 2.7 使用随机方式访问I/O

需求:

需要访问一个大的二进制文件,并读取指定位置的数据,而不是一个个的读到那里.

讨论:

指定的偏移地址等于数据块大小乘以块数.可以以此来定位到指定的数据块,并读取数据.比如,从文件的第七块来读取数据,块大小是48字节:

thefile = open('somebinfile', 'rb')
record_size = 48
record_number = 6
thefile.seek(record_size * record_number)
buffer = thefile.read(record_size)

需要注意的是,块数从0开始计数,所以record_number等于6.

上面的方法只适用于固定块大小的二进制文件,对于一般的文本文件可能就不适用了.在代码中,是以二进制方式打开文件的,只要是以二进制方式打开,你可以随意的seek和read,在关闭文件之前,你不用为了使用seek而再打开它一次.

相关说明:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.
   
    Argument offset is a byte count.  Optional argument whence defaults to
    0 (offset from start of file, offset should be >= 0); other values are 1
    (move relative to current position, positive or negative), and 2 (move
    relative to end of file, usually negative, although many platforms allow
    seeking beyond the end of a file).  If the file is opened in text mode,
    only offsets returned by tell() are legal.  Use of other offsets causes
    undefined behavior.
    Note that not all file objects are seekable.

Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?