我目前正在开发一个加密程序,并面临着用Python 3编写非文本文件的问题。
例如,这将起作用(定义了fEncode()):
text = ''
textFile = open(textFileName, 'r', encoding='utf-8')
for textLine in textFile:
text += 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, 'w', encoding='utf-8')
ciphertextFile.write(ciphertext)
ciphertextFile.close()这里textFileName = 'C:\aRandomTextFile.txt‘。但是,如果我将其替换为“C:\aRandomImage.png”,并替换
ciphertextFile = open(textFileName, 'w', encoding='utf-8')使用
ciphertextFile = open(textFileName, 'wb')然后试着
ciphertextFile.write(bytes(str(ciphertext, encoding='utf-8')))我得到了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Comp_Sci/Coding/chr_ord_5.py", line 466, in <module>
ciphertextFile.write(bytes(str(ciphertext, encoding='utf-8')))
TypeError: decoding str is not supported我做错什么了?
发布于 2015-10-12 17:49:02
你试过str.encode(ciphertext, encoding='utf-8')吗?
发布于 2015-10-12 17:48:40
问题在于生成字节字符串的方式。考虑以下几点,类似于您正在做的事情:
>>> bytes('banana')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
bytes('banana')
TypeError: string argument without an encoding或
>>> bytes(str('banana',encoding='utf-8'))
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
bytes(str('banana',encoding='utf-8'))
TypeError: decoding str is not supported但现在尝试另一种方法:
>>> bytes('banana'.encode('utf-8')) # redundant, see last example
b'banana'或
>>> bytes(ord(c) for c in 'banana')
b'banana'甚至只是:
>>> 'banana'.encode()
b'banana'现在您可以看到,bytes(str('banana',encoding='utf-8'))正在接受一个字符串,使它成为一个二进制字符串,将其转换为一个未编码的字符串,然后再次尝试从它中生成一个字节字符串。
希望这能有所帮助。
https://stackoverflow.com/questions/33086915
复制相似问题