簡體   English   中英

在python中讀取文件的特定字節

[英]Read specific bytes of file in python

我想指定一個偏移量,然后讀取文件的字節

offset = 5
read(5) 

然后閱讀下一個6-10等我讀到了關於搜索但我無法理解它是如何工作的,這些例子不夠描述。

seek(offset,1)返回什么?

謝謝

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

seek不會返回任何有用的東西。 它只是將內部文件指針移動到給定的偏移量。 下一次讀取將從該指針開始讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM