繁体   English   中英

有人来解释为什么这段代码对我不起作用?

[英]Come someone explain why this code won't work for me?

我有我正在编写的这个程序,它应该只使用一个。 需要 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()

在您的答案中,您用“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是一回事,但我错了prbly

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM