46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
|
import base64
|
||
|
import os
|
||
|
|
||
|
|
||
|
def base64_encode(data, output=None):
|
||
|
"""
|
||
|
:param data: Bytes or String or FileStream.
|
||
|
:param output: Output file stream, when the data parameter is the file stream valid.
|
||
|
:return: What type of data entering returns the same data type.
|
||
|
"""
|
||
|
if isinstance(data, bytes):
|
||
|
return base64.b64encode(data)
|
||
|
if isinstance(data, str):
|
||
|
return base64.b64encode(bytes(data, encoding='utf-8')).decode()
|
||
|
else:
|
||
|
return base64.encode(data, output)
|
||
|
|
||
|
|
||
|
def base64_decode(data, output=None):
|
||
|
"""
|
||
|
:param data: Bytes or String or FileStream.
|
||
|
:param output: Output file stream, when the data parameter is the file stream valid.
|
||
|
:return: What type of data entering returns the same data type.
|
||
|
"""
|
||
|
if isinstance(data, bytes):
|
||
|
return base64.b64decode(data)
|
||
|
if isinstance(data, str):
|
||
|
return base64.b64decode(bytes(data, encoding='utf-8')).decode()
|
||
|
else:
|
||
|
return base64.decode(data, output)
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
# e.g. Code bytes type.
|
||
|
print(base64_encode(bytes('Some text content.', encoding='utf-8')))
|
||
|
# e.g. Code string type.
|
||
|
print(base64_encode('Some text content.'))
|
||
|
# e.g. Read the file and encode and write to another file.
|
||
|
# 1.Create a test example file,
|
||
|
open('./example_of_base64_encode', 'w').write('Some text content.')
|
||
|
# 2.Then test,
|
||
|
print(base64_encode(open('./example_of_base64_encode', 'rb'), open('./example_of_base64_encode.base64', 'wb')))
|
||
|
# 3.Final cleanup.
|
||
|
os.remove('./example_of_base64_encode')
|
||
|
os.remove('./example_of_base64_encode.base64')
|