The application of Python base64 coding

Source: Internet
Author: User
Tags base64

Beginners Base64 Code, make a note

First, write a simple example:

Encodes a string and then decodes it, this example comes from the https://docs.python.org/2/library/base64.html

>>> Import base64
>>> encoded = base64.b64encode (' Data to be encoded ')
>>> encoded< c2/> ' ZGF0YSB0BYBIZSBLBMNVZGVK '
>>> data = base64.b64decode (encoded)
>>> data
' data to Be encoded '

Requirements: Converts a picture file into a base64 encoding, and then decodes

#import os
import base64

#这里我使用spyder IDE, the pictures are stored under the Pythondemo folder
#查看当前路径,
# OS.GETCWD ()
# Modify the path to the directory where the picture is located
#os. ChDir (' Xxx/xx/pythondemo ')

#打开文件, picture name 11.jpg, read
r_data = open (' 11.jpg ', ' RB ') in binary form )

data_string = R_data.read ()
# with base64 encoding
encode = base64.encodestring (data_string)
encoded2 = Base64.b64encode (data_string)
# Print encode
# decoding
decode = base64.decodestring (encode)
Decoded2 = Base64.b64decode (encoded2)

#写入文件
w_data = open (' 11w.dat ', ' WB ')
W_data.write (decode)

W_data2 = Open (' 112.dat ', ' WB ')
W_data2.write (DECODED2)



Related Article

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.