Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 495
rutav shah Avatar asked Feb 27 '26 01:02

rutav shah


1 Answers

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()
like image 93
wim Avatar answered Mar 01 '26 14:03

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!