【问题标题】:convert the content of a file in hex to base64 and print out the result将文件的十六进制内容转换为base64并打印出结果
【发布时间】:2019-02-24 22:08:01
【问题描述】:

所以我正在尝试创建一个非常简单的程序来打开文件,读取文件并使用 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== 作为输出

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 您好,感谢您的帮助!我收到一个错误:TypeError: fromhex() argument must be str, not _io.TextIOWrapper
    • 我已经在 Windows 上的 Python 2.7.14 和 2.7.10 以及 Linux 上的 Python 3.6.1 上测试了这段代码。都给出相同的结果。
    • 请参阅onlinegdb.com/HJzq14MKm 这显示了在 Python 3 下工作的代码
    【解决方案2】:

    您需要使用bytes.fromhex() 将文件test.txt 中的十六进制字符串编码为类似字节的对象,然后再将其编码为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=='
    

    【讨论】:

    • 您好,感谢您的回复,但它不起作用。我收到此错误:ValueError: non-hexadecimal number found in fromhex() arg at position 2
    • @lucky_dandu 啊抱歉我会编辑它,我从字符串复制粘贴而不是加载文件...只是快速确认:您使用的是 python 3 对吗?
    • 是的,我在 ubuntu 16 上。我设法纠正了一些在 Windows 上有效但在 ubuntu 上无效的东西......
    • 它适用于我的 python 3.5.2,我不知道你是如何得到非十六进制 ValueError 的
    • @lucky_dandu 答案是否有效,还是您仍然收到 ValueError?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2021-05-07
    相关资源
    最近更新 更多