UnicodeEncodeError:'charmap'编解码器无法对位置49-53中的字符进行编码:字符映射到<undefined>

时间:2015-12-19 17:42:13

标签: python-3.x unicode encode codec

这是我创建文件的代码

character = open(namecharacter + '.txt', 'wt')
    character.write('Name: ' + namecharacter + '\n\nClass: ' + category + '\n\nHealth: ♥♥♥♥♥\n\nStrenght: ' + str(strength_new) +
                    '\n\nDefense: ' + str(defense_new) + '\n\nDexterity: ' + str(dexterity_new) +
                    '\n\nRanged Attack: ' + str(ranged_new) + '\n\nMelee Attack: ' +
                    str(melee_new) + '\n\nSpeed: ' + str(speed_new))
    character.close()

然后它给出了这个错误代码:

Traceback (most recent call last):
  File "F:\Fantasy Board Game\Game Program\DandD style game.py", line 566, in <module>
str(ranged_new) + '\n\nMelee Attack: ' + str(melee_new) + '\n\nSpeed: ' + str(speed_new))
File "C:\Users\Jedidiah\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 19, in encode
  return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 49-53: character maps to <undefined>

错误的一行是:

str(melee_new) + '\n\nSpeed: ' + str(speed_new))

我知道以前曾经问过这个问题,但我并不是真的明白如何修复它而且我不知道为什么会发生这种情况。我之前已经声明了代码中的所有变量,并且所有变量都在其他代码行中工作。

1 个答案:

答案 0 :(得分:3)

您尝试打印的字符不在cp1252使用的默认编码open中。您可以传递要用作参数的编码,例如:

character = open(namecharacter + '.txt', 'wt', encoding='utf8')

完整示例(确保以声明的UTF-8源代码编码保存文件):

#coding: utf8

datafmt = '''\
Name:          {namecharacter}
Class:         {category}
Health:        ♥♥♥♥♥
Strength:      {strength_new}
Defense:       {defense_new}
Dexterity:     {dexterity_new}
Ranged Attack: {ranged_new}
Melee Attack:  {melee_new}
Speed:         {speed_new}
'''

player = {'namecharacter' : 'Mark',
          'category' : 'Wizard',
          'strength_new' : 10,
          'defense_new' : 100,
          'dexterity_new' : 15,
          'ranged_new' : 10,
          'melee_new' : 5,
          'speed_new' : 10}

with open(player['namecharacter'] + '.txt', 'w', encoding='utf8') as character:
    character.write(datafmt.format(**player))

输出:

Name:          Mark
Class:         Wizard
Health:        ♥♥♥♥♥
Strength:      10
Defense:       100
Dexterity:     15
Ranged Attack: 10
Melee Attack:  5
Speed:         10