Reputation: 59
I have some text written in text files, but accidentally they were written in byte format, e.g: b'hello'. When I try to read via python as a text file, I get the output as "b'hello'", but i need "hello". I tried to convert it by:
"b'hello'".decode('utf-8')
But this gives an error as str does not have decode method. Any help regarding this will be appreciated.
Following is an example of how the text files looks:
Upvotes: 0
Views: 220
Reputation: 154
your_byte_text = b'hello'
output = str(your_byte_text, 'utf-8')
print(output) # output: hello
Mentioned that your_byte_text is real byte data. Because if you run str(your_byte_text) the value will become "b'hello'"
one of the way to retrive string from file.
with open(file_path, 'r') as file:
data = file.read()
# the data is pure string like 'hello' already.
Upvotes: 1
Reputation: 118
Use b"hello"
The b
shouldn't be in the sting but before the string
If you want to convert a string from a file, do exec(f"variable = b"{old_variable}"")
Upvotes: 0