微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将文本文件转换为十六进制 - 换行问题

如何解决将文本文件转换为十六进制 - 换行问题

我正在尝试将文本文件转换为十六进制,然后再转换回文本。只要我不使用换行符,它就可以正常工作。

一个函数获取文件名并返回一个包含代表每个字母的整数的列表。

    block = []
    file = open(filename,'rb')
    content = file.read()
    
    hexstring = binascii.hexlify(content)

    for i in range(0,len(hexstring),2):
        block.append(int(hexstring[i:i+2],base=16))

    return block

这就是我转换回纯文本的方式。


for i in range(len(stringList)):
    tmp = stringList[i]
    for j in range(len(tmp)):
        hexString = str(hex(tmp[j]))
        hexString = hexString.replace('0x','') 
        pt = bytearray.fromhex(hexString).decode()
        plainText.append(pt)

代码很糟糕,但只要我没有换行就可以工作。然后我收到以下错误

pt = bytearray.fromhex(hexString).decode()
ValueError: non-hexadecimal number found in fromhex() arg at position 1

解决方法

尝试使用编解码器模块

import codecs

def encode():
    with open(file='sample.txt') as file:
        text = file.read()
    return codecs.encode(bytes(text,encoding='utf-8'),"hex")

def decode(encodedString):
    return codecs.decode(encodedString,'hex')


a = encode()
b = decode(a)

print(a)
print(b)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。