Python小程序:获取二进制文件的所有内容

接上一篇:Python小程序:获取文本文件的所有内容

有时候希望获取一个二进制文件的所有内容,但又不希望有打开文件、读文件、关闭文件这些繁琐的步骤,因此需要用一个小程序把这几个步骤封装起来,一句话完成所需要的获取文件内容的操作。为此,这里给出一个示例代码。


代码如下(get_bin_file.py):

#! /usr/bin/env python

import os

def get_bin_file(filename):
	'''
	Get the all content of the binary file.
	
	input: filename - the binary file name
	return: binary string - the content of the file. 
	'''

	if not os.path.isfile(filename):
		print("ERROR: %s is not a valid file." % (filename))
		return None

	f = open(filename, "rb")
	data = f.read()
	f.close()

	return data



调用示例:

>>> import get_bin_file
>>> content = get_bin_file.get_bin_file("not_exist_file")
ERROR: not_exist_file is not a valid file.
>>> content = get_bin_file.get_bin_file("./get_bin_file.py")
>>> print (content)
b'#! /usr/bin/env python\n\nimport os\n\ndef get_bin_file(filename):\n\t\'\'\'\n\tGet the all content of the binary file.\n\t\n\tinput: filename - the binary file name\n\treturn: binary string - the content of the file. \n\t\'\'\'\n\n\tif not os.path.isfile(filename):\n\t\tprint("ERROR: %s is not a valid file." % (filename))\n\t\treturn None\n\n\tf = open(filename, "rb")\n\tdata = f.read()\n\tf.close()\n\n\treturn data\n\n\n'
>>> content = get_bin_file.get_bin_file("./str_split.py.png")
>>> print(content)
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\t\x00×××××××××××××××××××××××××××××××××××××\xb5\xeb\x93\xbc2\x00\x00\x00\x00IEND\xaeB`\x82'
>>> 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值