hinanmu
hinanmu

Reputation: 151

How to read byte type string from text file

I have a txt file. And this file's content is a byte type, like this

b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n<html xmlns="http://www.w3.org/1999/xhtml">\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />\r\n<!--<META http-equiv=Page-Enter content=blendTrans(Duration=0.5)>\r\n<META http-equiv=Page-Exit content=blendTrans(Duration=0.5)> -->\r\n<title>\xba...'

How can I translate it into

value = b'...'  # txt file content

Upvotes: 0

Views: 794

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125388

You can use ast.literal_eval() to evaluate the bytes literal:

bytesobject = ast.literal_eval(filecontents)

Demo:

>>> import ast
>>> foo = "b'bytes value as a literal'"
>>> type(foo)
<class 'str'>
>>> ast.literal_eval(foo)
b'bytes value as a literal'
>>> type(ast.literal_eval(foo))
<class 'bytes'>

However, it would be much better if you could just fix the source of the error, which is the code that created that file in the first place. Presumably that code used str() on a bytes value to write the data to a text file, where it should instead have opened a file in binary mode.

Upvotes: 2

Related Questions