2015-03-31 18 views
5

voglio specificare un offset e quindi leggere i byte di un file comeLeggi byte specifici di file di in pitone

offset = 5 
read(5) 

e poi leggere il prossimo 6-10 ecc ho letto su cerco, ma non riesco a capire come funziona e gli esempi non sono abbastanza descrittivi.

seek(offset,1) restituisce cosa?

Grazie

+1

Un suggerimento: assicurarsi di aprire il file per l'accesso binario, ad esempio: 'open (filename, 'rb')'. – cdarke

risposta

4

Basta giocare con il REPL di Python per vedere di persona:

[...]:/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

while True: fo.seek (offset, 1) b = fo.read() stampa b facendo che B stampe tutti i byte ad eccezione del primo "Offset "quelli ... Sono solo confuso ... – user3124171

+0

L'OP non specifica da dove viene calcolato l'offset. Se è l'inizio del file, dovrebbe essere 'f.seek (6, 0)' o solo 'f.seek (6)'. Qui non farà alcuna differenza perché non c'erano letture intermedie sul file aperto per cambiare la posizione corrente del flusso. Dato che l'OP vuole i successivi cinque caratteri dopo un offset di sei, la lettura dovrebbe probabilmente essere 'f.read (5)'. –

3

seek non restituisce nulla di utile. Sposta semplicemente il puntatore del file interno sull'offset specificato. La prossima lettura inizierà a leggere da quel puntatore in poi.

+0

Beh, dovrebbe tornare 'none': P – inspectorG4dget

4

I valori per il secondo parametro di seek sono 0, 1, o 2:

0 - offset is relative to start of file 
1 - offset is relative to current position 
2 - offset is relative to end of file 

Ricordati che puoi controllare le 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.