文件编写Python,如何将变量打印到txt文件

时间:2015-03-21 14:37:49

标签: python sos file-writing

我正在尝试使用python将得分和名称的变量打印到.txt文件。

import random
import csv
import operator
import datetime


now = datetime.datetime.now() ## gets the exact time of when the user begins the test.

def main():
    global myRecord
    myRecord = []
    name = getNames()
    myRecord.append(name)
    record = quiz()


def getNames(): ## this function grabs first and lastname of the user
    firstName = input ("Please enter your first name") ## asks for users name
    surName = input("Please enter your surname") ## asks for users suername
    space = " "
    fullName =  firstName + space +surName ## puts data of name together to  make full name
    print("Hello")
    print (fullName)
    myRecord.append(fullName)
    return fullName ## this is a variable returned to main

def quiz():
    print('Welcome. This is a 10 question math quiz\n')
    score = 0 ## sets score to 0.
    for i in range(10): ## repeats question 10 times
        correct = askQuestion()## if the statement above if correct the program asks a question.
        if correct:
            score += 1## adds one to the score
            print('Correct!\n')## prints correct if the user gets a question correct.
        else:
            print('Incorrect!\n') ## prints incorrect if the user gets a question wrong.
            return 'Your score was {}/10'.format(score)

def randomCalc():
    ops = {'+':operator.add, ## selects one of the three operators
           '-':operator.sub, ## selects one of the three operators
           '*':operator.mul,} ## selects one of the three operators
    num1 = random.randint(0,12)    ## samples a number between 0 and 12
    num2 = random.randint(1,10)   ## zero are not used to stop diving by zero
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))  ## puts together the num1, the operator and num2 to form question
    return answer

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def myfileWrite (myrecord):
    with open('Namescore.txt', 'w') as score:
        score.write(fullName + '\n')




main()

这里是应该询问用户名称的完整代码,打印10个数学问题,然后将时间名称和分数保存到txt文件  如果你能帮忙请做 非常感谢

2 个答案:

答案 0 :(得分:2)

您的缩进不正确,您实际上从未调用该函数:

with open('Namescore.txt', 'w') as score:
    score.write(fullName + '\n')

答案 1 :(得分:0)

您编写的代码将在每次运行代码时重新生成文件。我相信这是正确的做法:

with open("Namescore.txt", "a") as file:
    file.write(name, score, "\n")  # I don't know what your vars are called

这将附加到文件而不是重写:)

如果你想按自己的方式去做,那么正确的方法是:

def writeScore(name, score):
    file = open("Namescore.txt", "a")
    file.write(name, score, "\n")
    file.close()

writeScore("Example Examlpus", 201)