在Python中将变量附加到文件中

时间:2014-12-20 15:04:08

标签: python

我在python中创建了一个刽子手游戏,我会稍微发布一下代码。我在代码中有变量,例如生命左边和用户试图猜测的单词。我想要做的就是一旦游戏结束并且用户赢了或输了我想要将该游戏的结果打印到文本文件中以便用户可以查看并查看该单词是什么以及他们有多少人生活已走了。可以用作猜词的单词当前是从名为hangman.txt的文本文件中读取的,正如您将在代码中看到的那样。

import random
guessed_letters = ''
lives_remaining = 15
turns = 10


try:
    f = open('hangman.txt', 'r')
    words = f.read().splitlines()
    f.close()

except IOError:
    print("Error, file does not exist")
    exit()

a = open('results.txt', 'w')
a.write('the resulst of hangman are')
a.close()

def pick_a_word():
    wordposition=random.randint(0,len(words)-1)
    return words[wordposition]
word = pick_a_word()
length = len(word)
print "word is", length,
print ("letters long")
print '_ ' * length

def get_guess():
    guess = raw_input('Guess a letter')
    return guess

guesses = ''
turns = 15
used = []

while turns > 0:
    failed = 0

    for char in word:
        if char in guesses:
            print char,

        else:
            print "_",
            failed += 1

    if failed == 0:
        print "you won"

        break
    print

    guess = raw_input("guess a character:")

    guesses += guess

    if guess not in word:

        turns -= 1
        print "wrong"

        print "you have", + turns, 'more guesses'

        if turns == 0:

            print "You loose"

b = open('results.txt', 'a')
b.write('the new word was' + word + 'The lives you had left were:' + turns)
b.close()

代码目前正常运行,直到游戏结束,然后打印出此错误消息

Traceback (most recent call last):
  File "/Hangman/hangmanAppend.py", line 75, in <module>
    b.write('the new word was' + word + 'The lives you had left were:' + turns)
TypeError: cannot concatenate 'str' and 'int' objects

3 个答案:

答案 0 :(得分:3)

turns包含整数,无法连接到字符串。只有字符串可以与其他字符串连接。因此,您需要将turns转换为字符串作为str(turns)。所以:

替换:

b.write('the new word was' + word + 'The lives you had left were:' + turns)

使用:

b.write('the new word was' + word + 'The lives you had left were:' + str(turns))

答案 1 :(得分:1)

b.write('the new word was' + word + 'The lives you had left were:' + str(turns))

将完成你的工作!!

答案 2 :(得分:0)

变量字具有字符串类型,并且转换为int类型,表明您收到这些错误的原因。

将行更改为...

b.write('the new word was' + word + 'The lives you had left were:' + str(turns))

它会将变量转换为字符串类型,然后你可以将它们连接起来。