0

我有这个代码:

# -*- coding: utf-8 -*-
import random
import os, glob

guessesTaken = 0

print('Hello! What is your name?')
name = raw_input()
number = random.randint(1, 20)
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
    print('Take a guess.') 
    guess = raw_input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

    if guess < number:
        print('Your guess is too low.')

    if guess > number:
        print('Your guess is too high.')

    if guess == number:
        break

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!')

xa=len(name)
#has= str(name) + '    ' + str(guessesTaken) + 


f='toplevel.data'
with open("f", "a") as myfile:
    myfile.write('name')
    myfile.write(': ')
    myfile.write(name)
    myfile.write('          ')


    if len(name)>7:
        myfile.write((xa-7)*' ')
    elif len(name)==7:
        myfile.write(40*' ')
    else:
        myfile.write((7-xa)*' ')
    myfile.write('score')
    myfile.write(': ')
    myfile.write(guessesTaken)

我有下一个问题,我想在这段代码的末尾打印 toplevel.data 的内容,但我不这样做。
谢谢你的帮助。
#('gfdsgdgdfgdfgdfgdfgdfgsdgdfgdfgdfgdfgdfgfdgdfgdsfgfdgdfgdfgdfgdfgdfgdfgdfgdf')

4

2 回答 2

1

首先,您可能想要替换with open("f", "a") as myfilewith open(f, "a") as myfile. 然后,在脚本的末尾,添加以下内容:

with open(f) as myfile:
    print myfile.read()
于 2012-08-23T14:55:28.393 回答
0

您正在写入一个名为"f"

with open(f, "a") as myfile:

或者

with open('toplevel.data',"a") as myfile
于 2012-08-23T14:55:18.437 回答