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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29376498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:30:05  来源:igfitidea点击:

Read specific bytes of file in python

pythonseek

提问by user3124171

I want to specify an offset and then read the bytes of a file like

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

offset = 5
read(5) 

and then read the next 6-10 etc. I read about seek but I cannot understand how it works and the examples arent descriptive enough.

然后阅读接下来的 6-10 等。我阅读了有关搜索的内容,但我无法理解它是如何工作的,并且示例的描述性不够。

seek(offset,1)returns what?

seek(offset,1)返回什么?

Thanks

谢谢

采纳答案by Santa

Just play with Python's REPL to see for yourself:

只需使用 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'

回答by Bryan Oakley

seekdoesn't return anything useful. It simply moves the internal file pointer to the given offset. The next read will start reading from that pointer onwards.

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

回答by Brian Burns

The values for the second parameter of seekare 0, 1, or 2:

的第二个参数的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

Remember you can check out the help -

记住你可以查看帮助 -

>>> 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.