Empty string when reading a file

MRAB google at mrabarnett.plus.com
Sun Apr 5 11:28:52 EDT 2009


nxrikjs at googlemail.com wrote:
> Hi,
> 
> I'm reading in a file of 250 bytes. At the 55th byte, read() will
> return an empty string although this isn't the end of the file. This
> is what I have:
> 
> for i in range(os.path.getsize("inputFile")):
>     bitsInFile = inputFile.read(1)
>     inputFile.seek(i)
>     byteFromFile = ord(bitsInFile)
> 
> Reading in 1 byte, then moving to the next byte and converting the
> character read to its decimal format for later bitwise operations.
> 
> I've omitted the ord() step and it does return 250 characters, a
> couple of these are empty strings, not just byte 55. Just to see what
> was going on, I changed the range to 280 and, sure enough, it returned
> 30 empty strings signifying the end of the file.
> 
> Why does it return an empty string when it's not the end of the file?
> 
Are you using Windows and opening the file as text instead of binary?

In text files a byte of value 26 indicates the end of the file, so
.read() would return an empty file.

Anyway, if the file is only 250 bytes long then you might as well
reading it all at once, something like this:

f = open("inputFile", "rb") # Open as _binary_.
data = [ord(byte) for byte in f.read()]
f.close()




More information about the Python-list mailing list