I have written a code where I can convert the text from a text file a.txt
into a binary string Binary
, now I want do the reverse,
In other words, I want to convert binary string Binary
into a text file b.txt
which has same text as the text file a.txt
,
how can I do that?
The code is given below, plz provide solution according to the code:
content = open('a.txt', 'r').read()
test_str = content
# using join() + ord() + format() ... Converting String to binary
Binary = ''.join(format(ord(i), 'b') for i in test_str)
# printing original string
print("The original string is : " + str(test_str))
# printing result
print("The string after Binary conversion : \n" + str(Binary))
Edit:
I tried to convert the binary string
Binary
into a text string but I got unknown character, which is not in the text filea.txt
.If I provide space in
''.join(format(ord(i), 'b') for i in test_str)
then I can not get a sentence in the string also, I get error, the string gets spaces, which i don't need, I need a complete string without space in the stringBinary
. I tried below code for reconverting :n = int(Binary, 2)
print(n.to_bytes((n.bit_length() + 7) // 8,'big').decode())
Disclaimer related to Duplication Post:
This is not a duplicate the post you are referring is different, the post asks about "in other words, if i have binary number, i want to convert it to a text file." which is completely different,