[英]Writing non-text files using Python 3
我目前正在开发一个加密程序,并且遇到使用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
我到底在做什么错?
问题出在您使字节字符串成为字符串的方式中。 考虑以下内容,与您正在执行的操作类似:
>>> 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'))
正在接收一个字符串,使其成为二进制字符串,将其转换为未编码的字符串,然后尝试将字节字符串输出再次。
希望能有所帮助。
您是否尝试过str.encode(ciphertext, encoding='utf-8')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.