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

Convert text file to hex - New Line problem

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

第一个函数获取文件名和returns一个包含代表每个字母的整数的列表。

    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

try using codecs modules

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)