佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > python用字節(jié)處理文件實例講解

python用字節(jié)處理文件實例講解

熱門標(biāo)簽:Win7旗艦版 百度AI接口 企業(yè)做大做強 電話運營中心 呼叫中心市場需求 語音系統(tǒng) 硅谷的囚徒呼叫中心 客戶服務(wù)

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

>>> with open(`dog_breeds.txt`, 'rb') as reader:
>>>     print(reader.readline())
b'Pug\n'

2、當(dāng)打開文件并單獨閱讀這些字節(jié)時,可以看到它確實是一個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'\r\n'
b'\x1a'
b'\n'

知識點擴展:

讀取文件的字節(jié)流數(shù)據(jù),將其轉(zhuǎn)換為十六進制數(shù)據(jù)

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()

讀取文件的字節(jié)流數(shù)據(jù),將其編碼為base64并輸出

import base64

def 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()

將十六進制文件轉(zhuǎn)化為字節(jié)流文件寫入

import struct

a = open("str.txt","r")#十六進制數(shù)據(jù)文件
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用字節(jié)處理文件實例講解的詳細內(nèi)容,更多關(guān)于python使用字節(jié)處理文件的資料請關(guān)注腳本之家其它相關(guān)文章!

標(biāo)簽:山西 喀什 安康 濟南 海南 山西 崇左 長沙

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python用字節(jié)處理文件實例講解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    内乡县| 郴州市| 凌源市| 五华县| 延津县| 湛江市| 利辛县| 留坝县| 同仁县| 南安市| 甘洛县| 山西省| 阳东县| 宿迁市| 光泽县| 乌拉特后旗| 隆化县| 孙吴县| 启东市| 荆门市| 张家界市| 彝良县| 灌云县| 张北县| 车险| 北川| 龙游县| 卓尼县| 兴文县| 辉县市| 岑巩县| 丹巴县| 乾安县| 团风县| 平遥县| 胶州市| 永胜县| 同心县| 紫云| 城步| 贵阳市|