Answers for "python load file as bytes"

1

python read file as bytes

#for small file:
file = open("sample.bin", "rb")
byte = file.read(1)
while byte:
    #do somthing with the byte
    byte = file.read(1)
file.close()

#-------------------------------

#for big file (biger the the memory):
def bytes_from_file(filename, chunksize=8192): #8192 Byte = 8 kB (kib)
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

#call it
for b in bytes_from_file('filename'):
    do_stuff_with(b)
Posted by: Guest on July-09-2021

Python Answers by Framework

Browse Popular Code Answers by Language