Problems using struct pack/unpack in files, and reading them.

Grant Edwards invalid at invalid.invalid
Fri Nov 13 16:44:49 EST 2015


On 2015年11月13日, kent nyberg <kent at z-sverige.nu> wrote:
> Though, as many times before, the problem was due to misunderstanding
> of how python works. I assumed file.read()[xx:yy] was to be
> understood as, in the file, read from index xx to place yy.

Nope.
 First, the 'file.read()' part is evaluated. That returns the
 entire contents of the file.
 Next, the '[xx:yy]' slice operation is done on the entire contents
 returned in the first step. The slice operation retuns bytes xx
 through yy-1 (inclusive), and discards the rest of the data.
> Is it true then to say that every .read of a file, places an
> index-offset (?) from where the next read starts?

Yes. a file object has a current index. A read() operation always
starts at that index. When you open the file, that index is 0. Each
time you read from the file, the index is advanced past the data that
was read. The seek() method sets that index to whatever you want.
> That is, I need to rewind the file, or else the read will start from
> where the last read stopped?

Exactly.
-- 
Grant Edwards grant.b.edwards Yow! Mr and Mrs PED, can I
 at borrow 26.7% of the RAYON
 gmail.com TEXTILE production of the
 INDONESIAN archipelago?


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /