读:
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 | |
c | char | string of length 1 | |
b | signed char | integer | |
B | unsigned char | integer | |
? | _Bool | bool | |
h | short | integer | |
H | unsigned short | integer | |
i | int | integer | |
I | unsigned int | integer or long | |
l | long | integer | |
L | unsigned long | long | |
q | long long | long | |
Q | unsigned long long | long | |
f | float | float | |
d | double | float | |
s | char[] | string | |
p | char[] | string | |
P | void * | 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()