Python读取二进制文件

时间:2020-12-05 03:17:18
import os
import sys
import socket mypath = sys.argv[1] if not os.path.exists(mypath):
print "The path %s does not exist!" % mypath
sys.exit(2) for f in [s for s in os.listdir(mypath) if os.path.splitext(s)[1] == ".csta"]:
outputName = f + ".csv"
fd = open(os.path.join(mypath, f), 'rb')
outputFd = open(os.path.join(mypath, outputName), 'w')
fd.seek(0, 0)
while True:
s = int(0)
for i in range(37632):
data = fd.read(2)
if len(data) == 0:
break
else:
s += socket.htons(int(data.encode('hex'), 16)) if len(data) == 0:
break
else:
outputFd.write("%d\n" %s)
fd.close()
outputFd.close()
print "%s >> %s" % (f, outputName)

程序思路:

  1. 使用os.listdir列出用户所给目录的所有文件;
  2. 使用os.path.splitext获得文件的后缀名,以便匹配到自己想要的文件的类型;
  3. 使用data.encode('hex')获得十六进制的字符,然后使用int(data, 16)将其转成十进制数字;