Python Applet: Get all the contents of a binary file

Source: Internet
Author: User

Next article: Python applets: getting all the content of a text file

Sometimes you want to get all the content of a binary file, but do not want to open the file, read the file, close the file, these steps need to be encapsulated with a small program, complete the operations required to obtain the file content in one sentence. Here is a sample code.


The Code is as follows (get_bin_file.py ):

#! /usr/bin/env pythonimport osdef get_bin_file(filename):'''Get the all content of the binary file.input: filename - the binary file namereturn: binary string - the content of the file. '''if not os.path.isfile(filename):print("ERROR: %s is not a valid file." % (filename))return Nonef = open(filename, "rb")data = f.read()f.close()return data

Call example:

>>> 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'>>> 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.