如何读取存储在文本文件中的字符串的值,然后转换为整数,并对值进行数学运算?

时间:2018-09-09 15:46:36

标签: python concatenation

我编写Python代码只有大约4周的时间。我正在写一个基于文本的小游戏,以学习和测试我所知道的一切。我可以轻松地使用输入到控制台中的整数形式的值来实现此目的,但是出于任何原因,我都无法使我的代码能够从文本文件中读取该值。

在程序的早期,我的代码将一个值保存到一个文本文件中,只是一个值,然后再打开同一文本文件,并基于一个非常简单的计算用一个新值覆盖该值。该计算是第一个值加上5。我花了很多时间在这个网站上阅读并浏览我的书,在这一点上,我很确定自己只是缺少一些明显的东西。

创建文档并设置值的第一段代码:

def set_hp(self):
    f = open('player_hp.txt', 'w')
    self.hitpoints = str(int(self.hitpoints))
    f.write(self.hitpoints)
    f.close()

这是麻烦部分...我已经注释了该问题所在的行。

def camp_fire():
    print
    print "You stop to build a fire and rest..."
    print "Resting will restore your health."
    print "You gather wood from the ground around you. You spark\n\
your flint against some tinder. A flame appears.\n\
You sit, and close your eyes in weariness. A peaceful calm takes you\n\
into sleep."
    f = open('player_hp.txt', 'r')
    orig_hp = f.readlines()
    orig_hp = str(orig_hp)
    f = open('player_hp.txt', 'w')
    new_value = orig_hp + 5    ##this is where my code breaks
    new_value = str(int(new_value))
    f.write(new_value)
    f.close()
    print "You have gained 5 hitpoints from resting. Your new HP are {}.".format(new_value)

这是我得到的错误:

  File "C:\Python27\Awaken03.py", line 300, in camp_fire
    new_value = orig_hp + 5
TypeError: cannot concatenate 'str' and 'int' objects

我知道您不能将字符串和整数连接在一起,但是我一直在尝试不同的方法将字符串转换为整数以进行快速数学运算,但是我似乎无法正确理解。

2 个答案:

答案 0 :(得分:0)

错误消息明确,您正在尝试将字符串与整数连接。您应该将行从以下位置更改:

new_value = orig_hp + 5

收件人:

new_value = str(int(orig_hp) + 5)

然后您可以使用上述值以字符串形式直接写入文件,如下所示:

##new_value = str(int(new_value))## Skip this line
f.write(new_value)

答案 1 :(得分:0)

f.readlines()返回行的列表,在您的情况下,类似['10']。因此str(orig_hp)是此列表的文本表示形式,例如'[\'10\']',您将无法将其解释为整数。

您可以只使用f.read()一次读取一个字符串中的整个文件(类似于'10',然后将其转换为整数:

orig_hp = int(f.read())