通过python3进行Unicode文件转换

2024-10-02 00:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在开发一个加密/解密程序,它可以很好地处理文本文件,但在处理二进制文件时遇到了问题。下面是一个问题示例:

假设我有一个PNG文件(filea),当我在记事本中打开它时,它看起来像:enter image description here

当我对它进行加密和解密时,我得到一个文件(文件B),看起来像:enter image description here

这两个文件实际上是相同的,只是文件B有一个奇怪的编码,它将unicode格式(如文件a中的第一个字符)转换为\x89,这并不是我真正需要的。在文件A中找到的任何新行也会变成\r\n在文件B中

我尝试了几种不同的方法来编写文件B,但我认为问题在于它以字符串形式返回的方式

 b'\x89PNG\r\n'b'\x1a...

在被解密之后。有没有什么办法我可以把所说的字符串转换成文件A中看到的有效的特许状

我正在附加写文件的代码,可能有必要

text = ''
textFile = open(textFileName, 'rb')
for textLine in textFile:
    text += str(textLine)
textFile.close()  

ciphertext = text
numPassCounter = 0
for password in passwords:
    ciphertext = fEncode(ciphertext, password, num_passwords[numPassCounter])
    numPassCounter += 1   

os.system("copy /y " + textFileName + " " + ciphertextFileName)
ciphertextFile = open(ciphertextFileName, 'wb')
ciphertextFile.write(bytes(ciphertext.encode()))
ciphertextFile.close()

if bool_chk_output:
    plaintext_r = ''
    plaintext_r_file = open(ciphertextFileName, 'r', encoding='utf-8')
    for plaintext_r_line in plaintext_r_file:
        plaintext_r += str(plaintext_r_line)
    plaintext_r_file.close()

    plaintext = plaintext_r
    rNumPassCounter = 0
    for rPassword in rPasswords:
        plaintext = fDecode(plaintext, rPassword, rNumPasswords[rNumPassCounter])
        rNumPassCounter += 1
    os.system("copy /y " + textFileName + " " + plaintextFileName)
    plaintextFile = open(plaintextFileName, 'wb')
    plaintextFile.write(bytes(plaintext.encode()))
    plaintextFile.close()

    if text == plaintext:
        print('Success!')
    else:
        print('Error! Plaintext does not match original text.')

为了避免混淆:fEncode()和fDecode()都有3个参数:2个字符串和一个整数


Tags: 文件字符串textinforcloseopenfile

热门问题