python用字節(jié)處理文件實例講解
1、可以在mode參數(shù)中添加’b’字符。所有適合文件對象的相同方法。然而,每種方法都希望并返回一個bytes對象。
>>> with open(`dog_breeds.txt`, ’rb’) as reader:>>> print(reader.readline())b’Pugn’
2、當打開文件并單獨閱讀這些字節(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’rn’b’x1a’b’n’
知識點擴展:
讀取文件的字節(jié)流數(shù)據(jù),將其轉換為十六進制數(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 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()
將十六進制文件轉化為字節(jié)流文件寫入
import structa = 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é)處理文件實例講解的詳細內容,更多關于python使用字節(jié)處理文件的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. jsp網(wǎng)頁實現(xiàn)貪吃蛇小游戲2. SpringMVC+Jquery實現(xiàn)Ajax功能3. JavaScript實現(xiàn)組件化和模塊化方法詳解4. ASP 信息提示函數(shù)并作返回或者轉向5. .Net Core和RabbitMQ限制循環(huán)消費的方法6. ASP.NET MVC遍歷驗證ModelState的錯誤信息7. ASP中if語句、select 、while循環(huán)的使用方法8. ASP實現(xiàn)加法驗證碼9. 刪除docker里建立容器的操作方法10. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明
