How to use quopri.decode() in Python
The quopri.decode() function in Python performs quoted-printable decoding on data with few non-printable characters.
To use the quopri.encode() function, the program needs to import the quopri module as shown below:
import quopri
Prototype and parameters
The function accepts input and output as non-optional parameters.
- The
inputandoutputparameters accept binary file objects. Thequopri.decode()function decodes the input file and writes the quoted-printable decoded data to the output file.
- The
headerparameter accepts aTrueorFalsevalue. The function decodes spaces as underscores if theheaderisTrue; otherwise, it leaves them unencoded.
Note:
quopri.decode()usesFalseas the default value ofheader.
Explanation
The quopri.decode() function decodes all 8-bit value characters encoded into a = and two hexadecimal digits, except printable ASCII characters. For example, =3D has a decimal value of 61 and is decoded as =.
All ASCII characters with decimal values from 33 to 126 are printable and decoded as well as encoded as themselves. An exception is = with an ASCII value of 61.
A space with ASCII value 9 and a tab with ASCII value 32 can be encoded as themselves.
Example
The following code demonstrates the use of the quopri.decode() function:
import quoprifrom io import BytesIO#-----------ENCODING-------------#example texttext = 'This text contains ünicöde'#create binary input fileinputFile= BytesIO((text).encode('utf-8'))#create binary output fileoutputFile = BytesIO()#generate encodingquopri.encode(inputFile, outputFile, quotetabs = True)#extract file contentprint("-----------ENCODING-------------")print(outputFile.getvalue())#----------DECODING--------------#create binary output fileoutputFile2 = BytesIO()#create binary input fileinputFile2 = BytesIO(b'This=20text=20contains=20=C3=BCnic=C3=B6de')#generate decoded dataquopri.decode(inputFile2, outputFile2)#extract outputoutput = outputFile2.getvalue()#extract textprint("-----------DECODING--------------")print(output.decode('utf-8'))
The example text contains two non-printable characters and three spaces.
The program creates input and output files using the BytesIO module. BytesIO creates an in-memory binary file-like object. Once created, the program can read from and write to it like a regular file.
The program displays the output through the getValue() function, which extracts the file’s contents.
- The first part of the program
takes the example input and generates its quoted-printable encoding through the
quopri.encode()function. - The spaces are encoded as =20 because the
quotetabsparameter wasTrueduring encoding. The program encodes Unicode characters ü and ö as =C3=BC and =C3=B6 respectively. - The encoded form is given as an input to the
quopri.decode()function. - The displayed decoded result is identical to the example text.
Note:
utf-8encoding of Unicode characters can take up to four bytes.
Free Resources