0

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: enter image description here

3
  • 2
    If you are reading the correct string already... would it work with just removing the preceding b' and ending '? someting like str[2:len(str)-1] Commented Mar 15, 2021 at 8:33
  • " they were written in byte format" - all that eventually gets written to a file is bytes. The problem lies in the way you read it, and depending on that, Python will convert the binary data to strings, if you let it do it by opening the file in text mode, or present it to you as sequences of bytes if you opened the file in binary mode. It looks like you did the latter. Commented Mar 15, 2021 at 8:42
  • @ppanero its not just str and byte has only the difference of b'' there are other characters that need to be converted Commented Mar 15, 2021 at 11:17

2 Answers 2

1
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.
Sign up to request clarification or add additional context in comments.

2 Comments

what is have is your_byte_text="b'hello'" and not your_byte_data=b'hello'
@AyushTiwari I have no idea about that. so I just post my way to get text string from text file as your reference.
0

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}"")

1 Comment

When i read from the text file and store it in the variable it is being store in the format variable = "b'hello'"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.