Python讀寫二進位制檔案

2021-06-08 23:47:21 字數 1995 閱讀 2677

讀:

file模式'rb'

import binascii

s_16 = binascii.b2a_hex(f.read(1))#2--->16

寫:file模式'wb'

import struct

f.write(struct.pack('b',int(s_16,16)))#16--->10,此處若不將16進製制資料轉換成10進製在轉換成位元組流直接寫進檔案的話,會與原檔案不同

struct.pack用於將python的值根據格式符,轉換為字串(因為python中沒有位元組(byte)型別,可以把這裡的字串理解為位元組流,或位元組陣列)。

struct.unpack做的工作剛好與struct.pack相反,用於將位元組流轉換成python資料型別。它的函式原型為:struct.unpack(fmt, string),該函式返回乙個元組

c語言中常用型別與python型別對應的格式符:

格式符c語言型別

python型別注x

pad byte

no value

cchar

string of length 1

bsigned

char

integer

bunsigned

char

integer

?_bool

bool

hshort

integer

hunsigned

short

integer

iint

integer

iunsigned

intinteger or long

llong

integer

lunsigned

long

long

qlong

long

long

qunsigned

long

long

long

ffloat

float

ddouble

float

schar

string

pchar

string

pvoid

*long

下面是乙個簡單的檔案加密程式,將位元組流前四位取出做異或操作連同其餘位元組寫入新檔案,再次執行即可解密。

import binascii

import struct

print(" -----encoder-----")

frpath = raw_input("enter source path: ")

fwpath = raw_input("enter target path: ")

keys = [9,4,8,6]

try:

fr = file(frpath,'rb')

fw = file(fwpath,'wb')

for i in range(4):

fr.seek(i)

s_16 = binascii.b2a_hex(fr.read(1))

s_10 = int(s_16,16)

s_10no = s_10 ^ keys[i]

s_10novalue = struct.pack('b',s_10no)

fw.write(s_10novalue)

fw.write(fr.read())

except ioerror:

print("----------------------------------------")

print("progress error")

finally:

print("----------------------------------------")

print("done successfully")

fr.close()

fw.close()

二進位制檔案讀寫

define crt secure no warnings include include include size t fread void buffer,size t size,size t count,file stream size t fwrite const void buffer,si...

python的二進位制檔案讀寫

總的感覺,python本身並沒有對二進位制進行支援,不過提供了乙個模組來彌補,就是struct模組。python沒有二進位制型別,但可以儲存二進位制型別的資料,就是用string字串型別來儲存二進位制資料,這也沒關係,因為string是以1個位元組為單位的。import struct a 12.34...

C 讀寫二進位制檔案

摘要 使用c 讀寫二進位制檔案,在開發中操作的比較頻繁,今天有幸找到一篇文章,遂進行了一些試驗,並進行了部分的總結。使用c 操作檔案,是研發過程中比較頻繁的,因此進行必要的總結和封裝還是十分有用的。今天在網上找到一篇,遂進行了部分的試驗,以記之,備後用。include 寫二進位制檔案 寫二進位制檔案...