Empty string when reading a file

N

nxrikjs

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?
 
M

MRAB

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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top