Search code examples
pythonpython-3.xbinaryfiles

Decoding Ascii Binary


So I've tried the code below and after running this code it simply prints " ". Can someone point out what I'm doing wrong, or what I could do to fix this

file1 = open("Binaryfile.bin","wb+")
v = bytes("Hello World","ascii")
file1.write(v)
v = file1.read()
v = v.decode('ascii')
print(v)
file1.close()

Solution

  • After the write operation, your position in the file is still positioned at the end of the bytes you've just written. So when you call read immediately, you read from the end of the file until, err.. the end of file. Ergo, you read (and print) an empty string.

    file1 = open("Binaryfile.bin","wb+")
    v = bytes("Hello World","ascii")
    file1.write(v)
    file1.seek(0)   # <--- rewind file!
    v = file1.read()
    v = v.decode('ascii')
    print(v)
    file1.close()