How to Convert a File to Base64 in Python?

Estimated read time 2 min read

To convert a file to Base64 in Python, you can use the base64 module available in Python’s standard library. Here’s an example of how you can do it:

import base64

file_path = 'file.txt'

with open(file_path, 'rb') as file:
    file_content = file.read()
    base64_content = base64.b64encode(file_content)

base64_string = base64_content.decode('utf-8')
print(base64_string)

In this example, 'file.txt' represents the path to the file you want to convert to Base64. Replace it with the actual path to your file.

The file is opened using open() in binary read mode ('rb'). The read() method is then used to read the file’s content, which is stored in the file_content variable as bytes.

Next, the base64.b64encode() function is applied to the file_content to encode it in Base64 format. The resulting encoded content is stored in the base64_content variable as bytes.

To obtain the Base64 string representation, base64_content is decoded using decode('utf-8'). The resulting string is assigned to the base64_string variable.

Finally, the base64_string is printed, which will display the Base64 representation of the file.

Note that the resulting Base64 string will include characters from the Base64 character set, which consists of uppercase letters, lowercase letters, numbers, the “+” symbol, and the “/” symbol.

Make sure that you have imported the base64 module at the beginning of your code to use its functionality.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply