我正在尝试将符号写入?python中的文本文件.我认为它与编码有关(utf-8).这是代码:
# -*- coding: utf-8 -*-
outFile = open('./myFile.txt', 'wb')
outFile.write("?")
outFile.close()
Run Code Online (Sandbox Code Playgroud)
而不是"?"我得到的黑色"â—".我怎样才能解决这个问题?
如果您使用的是 Python 2,请使用codecs.open代替open和unicode代替str:
# -*- coding: utf-8 -*-\nimport codecs\noutFile = codecs.open(\'./myFile.txt\', \'wb\', \'utf-8\')\noutFile.write(u"\xe2\x97\x8f")\noutFile.close()\nRun Code Online (Sandbox Code Playgroud)\n\n在 Python 3 中,将encoding关键字参数传递给open:
# -*- coding: utf-8 -*-\noutFile = open(\'./myFile.txt\', \'w\', encoding=\'utf-8\')\noutFile.write("\xe2\x97\x8f")\noutFile.close()\nRun Code Online (Sandbox Code Playgroud)\n