国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python用字節處理文件實例講解

瀏覽:2日期:2022-06-22 15:55:46

1、可以在mode參數中添加’b’字符。所有適合文件對象的相同方法。然而,每種方法都希望并返回一個bytes對象。

>>> with open(`dog_breeds.txt`, ’rb’) as reader:>>> print(reader.readline())b’Pugn’

2、當打開文件并單獨閱讀這些字節時,可以看到它確實是一個png文件:

>>> with open(’jack_russell.png’, ’rb’) as byte_reader:>>> print(byte_reader.read(1))>>> print(byte_reader.read(3))>>> print(byte_reader.read(2))>>> print(byte_reader.read(1))>>> print(byte_reader.read(1))b’x89’b’PNG’b’rn’b’x1a’b’n’

知識點擴展:

讀取文件的字節流數據,將其轉換為十六進制數據

def read_file(): with open(’./flag.zip’,’rb’) as file_byte:file_hex = file_byte.read().hex()print(file_hex)write_file(file_hex)def write_file(file_hex): with open(’new.txt’,’w’) as new_file:new_file.write(file_hex)if __name__ == ’__main__’: read_file()

讀取文件的字節流數據,將其編碼為base64并輸出

import base64def read_file(): with open(’./flag.zip’,’rb’) as file_byte:file_base64 = base64.b64encode(file_byte.read())print(file_base64)if __name__ == ’__main__’: read_file()

將十六進制文件轉化為字節流文件寫入

import structa = open('str.txt','r')#十六進制數據文件lines = a.read()res = [lines[i:i+2] for i in range(0,len(lines),2)]with open('xxx.xxx','wb') as f:for i in res:s = struct.pack(’B’,int(i,16))f.write(s)

以上就是python用字節處理文件實例講解的詳細內容,更多關于python使用字節處理文件的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 汕尾市| 桑日县| 孝昌县| 寻甸| 合山市| 健康| 东丰县| 南汇区| 青海省| 沙湾县| 孝感市| 横峰县| 武鸣县| 巢湖市| 清丰县| 紫阳县| 宝坻区| 闽清县| 湘乡市| 蒙阴县| 金堂县| 华容县| 淮北市| 呼玛县| 六安市| 巴楚县| 开远市| 滨海县| 察哈| 南昌市| 河间市| 昌乐县| 旅游| 咸丰县| 南川市| 台南县| 赤峰市| 蓬莱市| 黎城县| 福鼎市| 松原市|