读取 python 中文件的特定字节
Read specific bytes of file in python
我想指定一个偏移量,然后读取像
这样的文件的字节
offset = 5
read(5)
然后阅读接下来的 6-10 篇等。我读到了有关 seek 的内容,但我不明白它是如何工作的,而且示例描述性不够。
seek(offset,1)
returns什么?
谢谢
seek
return 没有任何用处。它只是将内部文件指针移动到给定的偏移量。下一次读取将从该指针开始读取。
自己玩玩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.
我想指定一个偏移量,然后读取像
这样的文件的字节offset = 5
read(5)
然后阅读接下来的 6-10 篇等。我读到了有关 seek 的内容,但我不明白它是如何工作的,而且示例描述性不够。
seek(offset,1)
returns什么?
谢谢
seek
return 没有任何用处。它只是将内部文件指针移动到给定的偏移量。下一次读取将从该指针开始读取。
自己玩玩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.