【问题标题】:How do I save this variable to a new text file?如何将此变量保存到新的文本文件?
【发布时间】:2015-09-20 00:58:21
【问题描述】:

所以我试图将一些密文保存到用户命名的新文本文件中,但是当我运行代码时,它会显示以下消息:

Please enter the name you wish the file to be called: cipher

Traceback (most recent call last):
  File "C:/Users/User/Documents/file figure.py", line 19, in <module>
    f.write(cipher_text_write)
  File "C:\Python34\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 '\x8e' in position 1: character maps to <undefined>

我设法弄清楚是我要保存的实际消息导致了问题。任何帮助将不胜感激!

这是我的代码:

cipher_text = " «²²µ ³¿ ´§³« ¯¹ µ´«²² "

filename = input("Please enter the name you wish the file to be called: ")
cipher_text_write = str(cipher_text)
cipher_filename = filename + ".txt"
f = open(cipher_filename,"w+")
f.write(cipher_text_write)
f.close()

【问题讨论】:

标签: python


【解决方案1】:

这里要理解的重要一点是,加密的结果只是一个比特流。这些位不一定对应一个合法的字符串。

您的密码文本包含无法编码为任何合法字符的字节模式。有很多方法可以解决这个问题,但最简单的方法是将文件作为二进制文件打开,或者将这些位编码为 base64 之类的内容,例如:

>>> import os
>>> import base64
>>> s = str(os.urandom(10000))
>>> encs=base64.b64encode(s)
>>> s2 = base64.b64decode(encs)
>>> cmp(s,s2)
0

当您想读回密码文本时,您需要按照您在写入文件时选择的解决方案,将包含密码文本的二进制文件打开或读取并解码位的 base64 表示。

【讨论】:

  • 通过这样做,我可以读回文件以使用密钥和偏移因子对其进行解密吗?
  • 这与你的解密能力无关。重要的是,您可以完全从文件中存储的数据重建cipher_text(这就是这个答案的意义所在)
  • 我已经修改了我的答案,使其更加全面。如果您还有任何问题,请告诉我。
  • @nitzanms 非常感谢,经过 4 小时尝试不同的方法后,我终于成功了。我最终用 utf-8 对其进行了编码。非常感谢!
  • 这不是个好主意。 UTF8 是一种字符编码,某些位模式可能无法在其中编码。这个问题是针对 C# 的,但 Jon Skeet 的回答与此相关:stackoverflow.com/questions/7996955/…
猜你喜欢
  • 2020-06-30
  • 1970-01-01
  • 2014-04-24
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多