Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Converting file to base64 encoding

Tags:

python

This is my code:

import base64  with open('/Users/Bob/test.txt') as f:     encoded = base64.b64encode(f.readlines())     print(encoded) 

I've based it on the base64 documentation. However, when I try running it with Python 2.7.1 and Python 3.2.2 I get the error:

    import base64   File "/Users/Bob/test.txt'", line 4, in <module>     encoded = base64.b64encode(f.readlines()) AttributeError: 'module' object has no attribute 'b64encode' 

Why can't the b64encode attribute be found?

like image 282
Randomblue Avatar asked Aug 18 '12 17:08

Randomblue


People also ask

How do you decode a file in Python?

decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.

How to use Base64 encoding in Python for image encoding?

As we mentioned previously, Base64 encoding is primarily used to represent binary data as text. In Python, we need to read the binary file, and Base64 encode its bytes so we can generate its encoded string. Let's see how we can encode this image: Create a new file encoding_binary.py and add the following: Let's go over the code snippet above.

How to Base64 decode a binary file?

When you are base64 decoding a binary file, you must know the type of data that is being decoded. For example, this data is only valid as a PNG file and not a MP3 file as it encodes an image. Once the destination file is open, we Base64 decode the data with base64.decodebytes, a different method from base64.b64decode that was used with strings.

How to encode and decode strings in Python?

In Python the base64 module is used to encode and decode data. First, the strings are converted into byte-like objects and then encoded using the base64 module. The below example shows the implementation of encoding strings isn’t base64 characters. Decoding Base64 string is exactly opposite to that of encoding.

How do I convert a string to a Base64 character?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits


1 Answers

You have a script named base64.py which is shadowing the stdlib module. Rename it.

like image 58
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 19:10

Ignacio Vazquez-Abrams