首页 > 解决方案 > 来人解释一下为什么这段代码对我不起作用?

问题描述

我有我正在编写的这个程序,它应该只使用一个。需要使用 for 来询问名称和分数是什么。此外,需要 for 将分数和名称写入文件。尝试运行它时出现错误提示“UnsupportedOperation: Not Readable”

Golf_File = open('golf.txt', 'w')

names = []
scores = []

for line in Golf_File:
    input("Please enter a players name: ")
    if name !='':
        break
    score = input("Please input the players score: ")
    if name != '' and score !="":
        golf.txt.write(name + "\n")(str(score) + "\n")
        Golf_File.close()





EDIT =
for line in Golf_File:
    Golf_File = open('golf.txt', 'w')
    names = input("Please enter a players name: ")
    score = input("Please input the players score: ")
    Golf_File.write(str(names) + "\n")
    Golf_File.write(str(scores) + "\n")

    Golf_File.close()

标签: python

解决方案


在您的回答中,您使用“w”打开了 Golf_File,这意味着在您想要读取文件时写入。要读取文件使用“r”而不是“w”又名

Golf_File = open('golf.txt', 'r')

for line in Golf_File:
    Golf_File = open('golf.txt', 'w')
    names = input("Please enter a players name: ")
    score = input("Please input the players score: ")
    Golf_File.write(str(names) + "\n")
    Golf_File.write(str(score) + "\n")

Golf_File.close()

我不是 100% 确定这可行,因为我不知道 golf.txt 里面有什么,但希望这可以帮助你。如有错误欢迎指正:)。我进行了一些编辑,例如更改错误的变量名称并将“r”(读取)更改为“wr”(写入和读取)。还要在循环之后关闭文件,这样它就可以工作不止一次。我以为 wr 是一回事,但我错了


推荐阅读