How to base64 encode and decode in Python

  1471 views   1 year ago Python

Base64 encoding and decoding is used when there needs to transfer or store data. Base64 converts text data into binary data.

Every programming language has own functions to encode and decode in Base64 format. Python language uses base64 module to easily methods to encode and decode in base64 format.

First create file and paste the below code.

import base64

text_data = "This is text message"
ascii_data = text_data.encode('ascii')
base64_byte_data = base64.b64encode(ascii_data)

encoded_data = base64_byte_data.decode('ascii')


Now run the command in Terminal to see output of encoded data.


To decode base64, same way create file and put the below code.

import base64

encoded_data = "VGhpcyBpcyB0ZXh0IG1lc3NhZ2U="
base64_byte_data = encoded_data.encode('ascii')
ascii_data = base64.b64decode(base64_byte_data)

text_data = ascii_data.decode('ascii')


And run the command in Terminal to see decoded data.

This is text message

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]