a = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdABCDabcd'
b = str(a)
print(b)
>>> b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x199\xd9\x9d\xfdABCDabcd'
print(bytes(b,'utf8'))
>>> b"b'\\x00\\xef\\xa2\\xa0\\xb3\\x8b\\x9d\\x1e\\xf8\\x98\\x199\\xd9\\x9d\\xfdABCDabcd'"
尝试写入文件,再读取也是如此,因为写进去的形式就是str字符
# 写入data.txt
a = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdABCDabcd'
with open('data.txt','w') as p:
p.write(str(a))
# 读取data.txt
with open('data.txt','r') as p:
line = p.readline()
print(line, type(line) == str)
>>> b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x199\xd9\x9d\xfdABCDabcd\\' True
print(bytes(line,'utf8'))
>>> b"b'\\x00\\xef\\xa2\\xa0\\xb3\\x8b\\x9d\\x1e\\xf8\\x98\\x199\\xd9\\x9d\\xfdABCDabcd\\\\'"
def readbytetxt(filename):
dic = {
'0': 0, '1': 1, '2': 2,
'3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8,
'9': 9, 'a': 10, 'b': 11,
'c': 12, 'd': 13, 'e': 14,
'f': 15,
with open(filename,'r') as p:
line = p.readline()
while line:
if line[-1] == '\n':
line = line[:-1]
i = 2
L = b''
while i+1 < len(line):
if line[i:i+2] == '\\x' and (line[i+2] in dic.keys()) and (line[i+3] in dic.keys()):
L += bytes([dic[line[i+2]]*16+dic[line[i+3]]])
i += 4
else:
L += bytes(line[i],'utf8')
i += 1
return L
line = p.readline()
print(readbytetxt('data.txt'))
>>> b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdABCDabcd'
def readbytetxt2(filename):
dic = {
'0': 0, '1': 1, '2': 2,
'3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8,
'9': 9, 'a': 10, 'b': 11,
'c': 12, 'd': 13, 'e': 14,
'f': 15,
dic2 = {
'a': '\a', 'b': '\b',
'f': '\f', 'n': '\n',
'r': '\r', 'v': '\v',
'\'': '\'', '\"': '',
'\\': '\\',
with open(filename,'r') as p:
line = p.readline()
while line:
if line[-1] == '\n':
line = line[:-1]
i = 2
L = b''
while i+1 < len(line):
if line[i:i+2] == '\\x' and (line[i+2] in dic.keys()) and (line[i+3] in dic.keys()):
L += bytes([dic[line[i+2]]*16+dic[line[i+3]]])
i += 4
elif line[i] == '\\' and line[i+1] in dic2.keys():
L += bytes(dic2[line[i+1]],'utf8')
i += 2
elif line[i:i+4] == '\\000':
L += bytes('\000','utf8')
i += 2
else:
L += bytes(line[i],'utf8')
i += 1
yield L
line = p.readline()
a = b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe first line\n\r\a\b\t\\\f\'\"\v\b\n\000'
b = b'\xa0\xdf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe second line\nn'
c = b'\xe0\xaf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x19\x39\xd9\x9d\xfdthe third line\\'
with open('data.txt','w') as p:
p.write(str(a)+'\n')
p.write(str(b)+'\n')
p.write(str(c))
line = readbytetxt2('data.txt')
print([a for a in line])
>>> [b'\x00\xef\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x199\xd9\x9d\xfdthe first line\n\r\x07\x08\\t\\\x0c\'"\x0b\x08\n\x00', b'\xa0\xdf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x199\xd9\x9d\xfdthe second line\nn', b'\xe0\xaf\xa2\xa0\xb3\x8b\x9d\x1e\xf8\x98\x199\xd9\x9d\xfdthe third line\\']