There are classmates in the afternoon Python Learn from the group , Use pyinstaller When packing source code , Because images are used in the code 、 Audio 、 Video and other resources , Can't package program into a single executable . Is there any way to save these resource files in the code ? I thought about , It should be possible . So , It took an hour , Write the following code , It's a good introduction .
This code can convert the binary file to python Script files , For other scripts to reference . At the end of the code, there are some examples , You can take any picture for demonstration . In addition to storing binary data , There are also two ways :
# -*- coding: utf-8 -*-
""" With python Modular storage 、 Use binary """
import os
import base64
from io import BytesIO
def bin2module(bin_file, py_file=None):
""" Binary files are converted to python modular
bin_file - Binary file name
py_file - Generated module filename , The binary file name is used by default , Just change the suffix
"""
fpath, fname = os.path.split(bin_file)
fn, ext = os.path.splitext(fname)
if not py_file:
py_file = os.path.join(fpath, '%s.py'%fn)
with open(bin_file, 'rb') as fp:
content = fp.read()
content = base64.b64encode(content)
content = content.decode('utf8')
with open(py_file, 'w') as fp:
fp.write('# -*- coding: utf-8 -*-\n\n')
fp.write('import base64\n')
fp.write('from io import BytesIO\n\n')
fp.write('content = """%s"""\n\n'%content)
fp.write('def get_fp():\n')
fp.write(' return BytesIO(base64.b64decode(content.encode("utf8")))\n\n')
fp.write('def save(file_name):\n')
fp.write(' with open(file_name, "wb") as fp:\n')
fp.write(' fp.write(base64.b64decode(content.encode("utf8")))\n')
if __name__ == '__main__':
""" Test code """
# Convert image file to img_demo.py
bin2module('forever.png', 'demo.py')
# Import the demo modular
import demo
# use pillow Open the image , verification demo Modular get_fp(): Return binary IO object ( Class file object )
from PIL import Image
im = Image.open(demo.get_fp())
im.show()
# Save as local file , verification demo Modular save(): Save the file
demo.save('demo_save.png')