创建一个写入文件的函数

Creating a function to write to a file

我最近刚开始为我的游戏开发编写代码 class,运行 遇到了问题。部分作业是创建一个允许我们通过用户输入写入文件的函数。我相信我已经把所有东西都记下来了,除了我实际上不能写入文件?我说的函数是: def write_file() 和列表中的选项9。任何和所有的帮助表示赞赏。谢谢。

enter = 0
start = 0
Roger = ()
read = open("read.txt", "r")
x = read.read()
read1 = open("read.txt", "w")



def read_file(read):
    return open(read)

def write_file(read1):
    read1 = open("read.txt", "w")
    read1.write(input())
    read1.close()
    return read1

def update_score(scores, person, amount):
    for score in scores:
        if score[0].lower() == person.lower():
            score[1] += amount
    return scores

def update_score1(scores, person, amount):
    for score in scores:
        if score[0].lower() == person.lower():
            score[1] -= amount
    return scores

def addition(num1):
    return num1 + num1

def square(num):
    print("I'm in square")
    return num * num

def display(message):
    """Display game instuctions"""
    print(message)

def instructions():
    """Display game instuctions"""
    print("Welcome to the world's greatest game")


def main():
    str1 = ["Roger", 3456]
    str2 = ["Justin", 2320]
    str3 = ["Beth", 1422]
    instructions()
    scores = [str1, str2, str3]

    start = input("Would you like to view the high score options? y/n ")
    if start == "y":
        print("""\
        Hello! Welcome to the high scores!
        Here are the current high score leaders!:
        """)
        print(scores)
        print("""\n\
        0 - Sort high scores
        1 - Add high score
        2 - Reverse the order
        3 - Remove a score
        4 - Square a number
        5 - Add 2 numbers together
        6 - Add to a score
        7 - Subtract from a score
        8 - Read a file
        9 - Write to a file
        """)
        option = int(input("Please enter your selection "))
        while option < 8:
            print(scores)            
            if option == 0:
                scores.sort()
                print("These are the scores sorted alphabetically")
                print(scores)
                option = option = int(input("Please enter your selection"))
            elif option == 1:
                print(scores)
                print("Please enter your name and score; After entering your name, hit the return key and enter your score")
                name = input()
                score = int(input())
                entry = (name,score)
                scores.append(entry)
                print(scores)
                option = option = int(input("Please enter your selection"))
            elif option == 2:
                print(scores)
                scores.reverse()
                print("\nHere are the scores reversed")
                print(scores)
                option = option = int(input("Please enter your selection"))
            elif option == 3:
                print(scores)
                print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
                name1 = input()
                score1 = int(input())
                remove = (name1,score1)
                scores.remove(remove)
                print(scores)
                option = option = int(input("Please enter your selection"))
            elif option == 4:
                val = int(input("Give me a number to square"))
                sqd = square(val)
                print(sqd)
                option = option = int(input("Please enter your selection"))
            elif option == 5:
                val0 = int(input("Give me one number"))
                val1 = int(input("Give me another number"))
                addi = (val0 + val1)
                print(addi)
                option = option = int(input("Please enter your selection"))
            elif option == 6:
                print(scores)
                sc0 = input("Please enter player whose score you would like to increase. ")
                sc1 = int(input("Please enter the amount would would like to add to their score. "))
                scores = update_score(scores, sc0, sc1)
                print(scores)                          
                option = option = int(input("Please enter your selection"))
            elif option == 7:
                sc2 = input("Please enter player whose score you would like to decrease. ")
                sc3 = int(input("Please enter the amount you would like to subtract from their score. "))
                scores = update_score1(scores, sc2, sc3)
                print(scores)
        while option <= 9:
            if option == 8:
                print(read.readlines())
                read.close()
                option = option = int(input("Please enter your selection "))                
            if option == 9:
                print(read.readlines())

                print(read.readlines())
                read1.close()
                option = option = int(input("Please enter your selection "))      



main()

您的 write_file 代码看起来不错,但您的程序中没有任何地方实际调用了 write_file 函数。也许你应该先找到你想调用它的地方。

你不应该带参数,只需打开文件并写入,如果你只是存储输出则不需要 return:

def write_file():
    inp = input("Enter filename to save data to:")
    with open(inp, "w") as f:
         f.write(input("Enter data to save:"))

您还使用了 return open(read),看起来您正试图对您在代码开头打开的文件对象调用 open

在你的主循环中,你一直调用 read.readlines() 这将不起作用,一个文件对象 return 有它自己的迭代器,它在一次调用 readlines 后就耗尽了,当然赢了'关闭文件后工作,每次都必须重新打开,使用 read.seek(0) 或将对 readlines 的第一次调用存储在变量中,然后使用它。我建议您不要在任何地方都使用相同的变量,因为这会使您的代码混乱并导致问题。