我无法打印文件的内容

时间:2012-08-23 14:52:07

标签: python

我有这段代码:

# -*- 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')

2 个答案:

答案 0 :(得分:1)

首先,您可能希望将with open("f", "a") as myfile替换为with open(f, "a") as myfile。然后,在脚本的末尾添加以下内容:

with open(f) as myfile:
    print myfile.read()

答案 1 :(得分:0)

您正在写入名为"f"

的文件
with open(f, "a") as myfile:

with open('toplevel.data',"a") as myfile