Encode and decode uuencode files using Python

PythonServer Side ProgrammingProgramming

It is a common requirement during file transfers to encode and decode them for various reasons like encryption, compression or just because they are going to be processed by different OS or file reading programs. The uuencode module helps us on both encoding and decoding files as shown below.

Encode the file

We will use the below image for encoding and later decoding it to get it back.

In the below program we use the encode function to encode the given image and read the content of the file after encoding.

Example

import uu

infile = "E:\\tp_logo.JPG"

uu.encode(infile, 'encoded_logo.JPG')
f = open("E:\\TP\\encoded_logo.JPG",'r')
print(f.read())

Running the above code gives us the following result −

Output

begin 666 tp_logo.JPG
M_]C_X 02D9)1@ ! 0$ D "0 #_X1"*17AI9@ 34T *@   @ ! $[ (
M ( (2H=I 0   ! (4IR= $   0 0<NH< < @,   /@
M <Z@   @                                    
M …………………………….

Decode

next we use the decode function of the module and create the image named decoded_logo.JPG. As you can see the decoded image matches the original image.

Example

import uu
uu.decode('encoded_logo.JPG','decoded_logo.JPG')

Running the above code gives us the following result −

Output

raja
Published on 28-Dec-2020 15:27:25
Advertisements