将十六进制文件的内容转换为base64并打印出结果

时间:2018-09-20 14:43:37

标签: python python-3.x type-conversion base64 hex

因此,我正在尝试创建一个非常简单的程序来打开文件,读取文件并使用python3将文件中的内容从十六进制转换为base64。

我尝试过:

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

但是我得到了错误:

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

我尝试了其他多种方法,但总是得到相同的错误。

在test.txt中的

是:

4B

如果你们能向我解释我做错了,那就太好了。

谢谢

编辑: 我应该得到Sw==作为输出

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题。您的代码适用于Python <= 2.7,但适用于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)

答案 1 :(得分:0)

您需要先使用test.txt将文件bytes.fromhex()中的十六进制字符串编码为类似字节的对象,然后再将其编码为base64。

import base64

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

print(encoded)

您应始终使用with语句打开文件,以在完成后自动关闭I / O。

在空闲状态:

>>>> import base64
>>>> 
>>>> with open('test.txt', 'r') as file:
....     content = file.read()
....     encoded = base64.b64encode(bytes.fromhex(content))
....     
>>>> encoded
b'Sw=='
相关问题