2015-03-31 149 views
5

文件的特定字節我想指定偏移量,然後讀取文件的字節像閱讀蟒蛇

offset = 5 
read(5) 

,然後閱讀未來6-10等我讀到尋找,但我無法理解它如何工作以及這些示例不足以描述。

seek(offset,1)的回報是什麼?

感謝

+1

提示:確保您打開二進制訪問文件,例如:'open(filename,'rb')'。 – cdarke 2015-03-31 19:11:01

回答

4

與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' 
+1

而真:通過這樣做,片B印的所有字節,除了第一 fo.seek(偏移,1) B = fo.read() 印片B 「偏移「那些......我只是困惑...... – user3124171 2015-03-31 19:14:51

+0

OP沒有指定從哪裏計算偏移量。如果它是文件的開頭,它應該是'f.seek(6,0)'或者只是'f.seek(6)'。這裏沒有什麼區別,因爲在打開的文件中沒有中間讀取來改變當前流的位置。由於OP需要六個偏移量之後的下五個字符,讀取應該是'f.read(5)'。 – 2015-03-31 19:15:07

3

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

+0

那麼,它應該返回'None':P – inspectorG4dget 2015-03-31 19:09:08

4

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