I understand that there are similar questions, but I do not understand them so here goes: I have bytes (encoded from a string) in a string form (read from a file). When I try to decode the bytes, I get an error saying that it is a string, not bytes. I understand it is in the wrong form, but do I not have the correct information? How can I convert bytes in a string back to bytes? I will also note I know this is not a secure password method and will not be used as one. (I am using python 3)
I've done some research into how I can fix this, but I am very new and either did not understand it or could not apply it. I though this would work but it does not:
password=bytes(password, 'cp037')
Oh well. Here is a short version of the code I have:
#writing to the file
password="example"
password=password.encode('cp037')
password=str(password)
f=open("passwordFile.txt", "w+")
f.write(password)
f.close
#reading from the file
f=open("passwordFile.txt","r")
password=f.read()
#this is where I need to turn password back into bytes
password=password.decode('cp037')
print(password)
I expected to get example as output, but have a error: AttributeError: 'str' object has no attribute 'decode'
A quick possibility to convert from a string representation of bytes literals
"b'\x85\xa7\x81\x94\x97\x93\x85'"
to the actual bytes would be
bytes_as_bytes = eval(bytes_literals_as_str)
i.e.
bytes_as_bytes = eval("b'\\x85\\xa7\\x81\\x94\\x97\\x93\\x85'")
write byte, read byte and convert into string using decode
#writing to the file
password="example"
password=password.encode('cp037')
#password=str(password) (remove this line)
f=open("passwordFile.txt", "wb")
f.write(password)
f.close()
#reading from the file
f=open("passwordFile.txt","rb")
password=f.read()
#this is where I need to turn password back into bytes
y=password.decode('cp037')
print(y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With