Oliver
Oliver

Reputation: 3682

Reliably read n bytes from file

I have a python program that needs to read N bytes from a file at certain offset (and write to another file). This is currently done using python's low-level interface os.read(), not file object due to other reasons. The file has been stat(), so it is certain that much data exists. My question is, will python try its best to return N bytes, or do I need to do it as it was coded in C, where such read needs to be put in a loop, check returned bytes for each read, until N bytes has been read. I hope this is to be avoided if python is already doing that internally.

Upvotes: 2

Views: 250

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122282

os.read() is a low-level call using the C stdlib calls directly, only translating between Python and C types. See the source code for the POSIX version for example.

You'll have to treat it exactly like a C call; you'll have to loop just like you would in C code.

Upvotes: 1

os.read could even do EINTR on signals (Python 3.2), see for example this bug entry in the issue database. The behaviour should be fixed W.R.T. EINTR semantics in upcoming Python 3.5.

Upvotes: 0

Related Questions