简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM