将bytes对象转换为python中的string对象



python代码

#!python3
import sys
import os.path
import codecs
if not os.path.exists(sys.argv[1]):
print("File does not exist: " + sys.argv[1])
sys.exit(1)
file_name = sys.argv[1]
with codecs.open(file_name, 'rb', errors='ignore') as file:
file_contents = file.readlines()
for line_content in file_contents:
print(type(line_content))
line_content = codecs.decode(line_content)
print(line_content)
print(type(line_content))

文件内容:Log.txt

b'x03x00x00x00xc3x8axc3xacRbx00x00x00x00042284899:ATBADSFASF:DSF456582:USrn1'

输出:

python3 file_convert.py Log.txt                                                                                                                                               ✔  19:08:22 
<class 'bytes'>
b'x03x00x00x00xc3x8axc3xacRbx00x00x00x00042284899:ATBADSFASF:DSF456582:USrn1'
<class 'str'>

我试过下面所有的方法

line_content = line_content.decode('UTF-8')
line_content = line_content.decode()
line_content = codecs.decode(line_content, 'UTF-8')

有其他的方法来处理这个吗?
line_content变量仍然保存字节数据,只是类型更改为str,这有点令人困惑。

Log.txt中的数据是pythonBytes对象的字符串表示形式。这很奇怪,但我们可以处理它。因为它是一个Bytes字面量,求值它,这将它转换为一个真正的pythonBytes对象。现在还有一个问题,那就是它的编码是什么。

我不认为使用codecs.open有任何优势。这是python 2.7中读取unicode文件的一种方式,在python 3中通常不需要。猜测UTF-8,您的代码将是

#!python3
import sys
import os
import ast
if not os.path.exists(sys.argv[1]):
print("File does not exist: " + sys.argv[1])
sys.exit(1)
file_name = sys.argv[1]
with open(file_name) as file:
file_contents = file.readlines()
for line_content in file_contents:
print(type(line_content))
line_content = ast.literal_eval(line_content).decode("utf-8")
print(line_content)
print(type(line_content))

我认为这是一个列表,而不是字符串。当你看到以(反斜杠)开头的字节串时,它可能是一个列表

试试这个

decoded_line_content = list(line_content)

最新更新