如何传递生成db输入(S1)的所有内容,从那里加载它(s2)并将其正确地传回文件中?
import time,os,sys,base64
s = "Hello World!\r\nHeyho"
#with s1 i make an input to the database; with s2 I select it -> works most time
s1 = base64.b64encode(s.encode("UTF-8")).decode("UTF-8") #print("Base64 Encoded:", s1)
s2 = base64.b64decode(s1.encode("UTF-8")).decode("UTF-8") #print(s2)
#example that I try to save it in a file:
s3 = "PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+"
with open("C:\\Users\\001\\Downloads\\Output.txt", "w") as text_file:
text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delete the signs日志:
C:\Users\001\Downloads>python trythis.py
Traceback (most recent call last):
File "trythis.py", line 11, in <module>
text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delelte signs
File "C:\Users\001\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u25b7' in position 28: character maps to <undefined>编辑:我在修窗户。
C:\Users\001\Downloads>python -V
Python 3.5.2发布于 2019-08-13 12:48:59
问题是您以文本模式打开文件,但不指定编码。在这种情况下,将使用系统默认编码,这在任何系统上都可能不同。
解决方案:将encoding参数指定给开放()。
顺便提一句:你为什么要.decode('UTF-8')?它确实有效,但是由于数据是make 64编码的,我认为ASCII解码会更有意义。此外,您应该只在I/O边界进行编码/解码(在本例中是这样,在写入文件时是这样),尽管您可能只是为了测试/演示目的而这样做的。
更新:
显然,你的Base64 64编码数据也是UTF-8编码的(第一个UTF-8,然后是Base64),所以这就是为什么你需要首先解码,然后UTF-8-解码它。
以下是一个可移植的工作示例:
import base64
b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'
decoded_text = base64.b64decode(b64_encoded_text).decode('utf-8')
with open('Output.txt', 'wt', encoding='utf-8') as text_file:
text_file.write('Ausgabe: %s' % decoded_text)尽管只将原始二进制(UTF-8编码)数据写入文件甚至更容易:
import base64
b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'
with open('Output.txt', 'wb') as file:
# file.write(b'Ausgabe: ') # uncomment if really needed
file.write(base64.b64decode(b64_encoded_text))发布于 2019-08-13 12:36:33
404似乎是正确的。您的代码在我的系统中使用Python 3运行得很好。可能发生的情况是,当您运行python trythis.py时,Windows将Python2作为默认的
你会发现你的Python 3安装
C:\Users\YourUserName\AppData\Local\Programs\Python\
目录中,它应该有一个名为Python37-32或类似的文件夹。要么在该文件夹的bin目录中使用Python3二进制文件(通过在命令提示符中指定完整路径)
C:\Users\YourUserName\AppData\Local\Programs\Python\Python37-32\bin\python trythis.py或者将该文件夹添加到PATH环境变量(并从其中删除python 2路径)。
https://stackoverflow.com/questions/57477217
复制相似问题