在python中读取文件的特定字节

在python中读取文件的特定字节,python,seek,Python,Seek,我想指定一个偏移量,然后读取文件的字节,如 offset = 5 read(5) 然后阅读下一篇6-10等。我读了关于seek的文章,但我不理解它是如何工作的,而且例子描述得不够 seek(偏移量,1)返回什么 谢谢seek不会返回任何有用的内容。它只是将内部文件指针移动到给定的偏移量。下一次读取将从该指针开始读取。只需使用Python的REPL即可查看: [...]:/tmp$ cat hello.txt hello world [...]:/tmp$ python Python 2.7

我想指定一个偏移量,然后读取文件的字节,如

offset = 5
read(5) 
然后阅读下一篇6-10等。我读了关于seek的文章,但我不理解它是如何工作的,而且例子描述得不够

seek(偏移量,1)
返回什么


谢谢

seek
不会返回任何有用的内容。它只是将内部文件指针移动到给定的偏移量。下一次读取将从该指针开始读取。

只需使用Python的REPL即可查看:

[...]:/tmp$ cat hello.txt 
hello world
[...]:/tmp$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('hello.txt', 'rb')
>>> f.seek(6, 1)    # move the file pointer forward 6 bytes (i.e. to the 'w')
>>> f.read()        # read the rest of the file from the current file pointer
'world\n'

seek
的第二个参数的值为0、1或2:

0 - offset is relative to start of file
1 - offset is relative to current position
2 - offset is relative to end of file
请记住,您可以查看帮助-

>>> help(file.seek) Help on method_descriptor: 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. >>>帮助(file.seek) 有关方法\u描述符的帮助: 寻找(…) 寻道(偏移量[,从何处])->无。移动到新文件位置。 参数偏移量是字节计数。默认为的可选参数 0(从文件开始的偏移量,偏移量应大于等于0);其他值为1 (相对于当前位置移动,正或负)和2(移动 相对于文件结尾,通常为负数,尽管许多平台允许 查找文件结尾以外的内容)。如果文件以文本模式打开, 只有tell()返回的偏移量是合法的。使用其他偏移量会导致 未定义的行为。 请注意,并非所有文件对象都是可查找的。
那么,它应该返回
None
:Pseek()返回它现在在文件中指向的索引。如果将o指向文件长度以外的位置或使用相对seek()命令,这也很有用。提示:确保打开文件进行二进制访问,例如:
open(filename,'rb')
。如果为True:fo.seek(offset,1)b=fo.read()打印b,则b将打印除第一个“offset”字节以外的所有字节。。。我只是感到困惑…OP没有指定从何处计算偏移量。如果它是文件的开头,那么它应该是
f.seek(6,0)
或者只是
f.seek(6)
。在这里没有区别,因为在打开的文件上没有中间读取来更改当前流位置。由于OP希望在偏移量为六个字符后再输入五个字符,因此读取值可能应该是
f.read(5)