Python 存儲和讀取ASCII碼形式的byte數據

 Python可以存byte數據到txt,但不要用str的方式直接存,轉成數字列表儲存,這樣方便讀取

L = []
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'
print(a)
for each in a:
    L.append(int(each))
with open('data.txt','w') as p:
    p.write(str(L))
print(L)
>>> [0, 239, 162, 160, 179, 139, 157, 30, 248, 152, 25, 57, 217, 157, 253, 116, 104, 101, 32, 102, 105, 114, 115, 116, 32, 108, 105, 110, 101, 10, 13, 7, 8, 9, 92, 12, 39, 34, 11, 8, 10, 0]


with open('data.txt','r') as p:
    line = p.readline()
print(b''.join([bytes([int(i)]) for i in line[1:-1].split(',')]))
>>> 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'

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章