0

So i'm trying to create a very simple program that opens a file, read the file and convert what is in it from hex to base64 using python3.

I tried this :

file = open("test.txt", "r")
contenu = file.read()
encoded = contenu.decode("hex").encode("base64")
print (encoded)

but I get the error:

AttributeError: 'str' object has no attribute 'decode'

I tried multiple other things but always get the same error.

inside the test.txt is :

4B

if you guys can explain me what I do wrong would be awesome.

Thank you

EDIT: i should get Sw== as output

lucky simon
  • 241
  • 1
  • 6
  • 22

2 Answers2

0

This should do the trick. Your code works for Python <= 2.7 but needs updating in later versions.

import base64
file = open("test.txt", "r")
contenu = file.read()
bytes = bytearray.fromhex(contenu)
encoded = base64.b64encode(bytes).decode('ascii')
print(encoded)
stx101
  • 271
  • 1
  • 7
  • Hi, thanks for trying to help! I get an error: TypeError: fromhex() argument must be str, not _io.TextIOWrapper – lucky simon Sep 20 '18 at 16:00
  • I've tested this code on Python 2.7.14 and 2.7.10 on Windows and Python 3.6.1 on Linux. All give the same result. – stx101 Sep 21 '18 at 07:08
  • Please see https://www.onlinegdb.com/HJzq14MKm This shows the code working under Python 3 – stx101 Sep 21 '18 at 08:49
0

you need to encode hex string from file test.txt to bytes-like object using bytes.fromhex() before encoding it to base64.

import base64

with open("test.txt", "r") as file:
    content = file.read()
    encoded = base64.b64encode(bytes.fromhex(content))

print(encoded)

you should always use with statement for opening your file to automatically close the I/O when finished.

in IDLE:

>>>> import base64
>>>> 
>>>> with open('test.txt', 'r') as file:
....     content = file.read()
....     encoded = base64.b64encode(bytes.fromhex(content))
....     
>>>> encoded
b'Sw=='
deadvoid
  • 1,270
  • 10
  • 19