简体   繁体   中英

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

I have this program I am writing and it's supposed to only use one for. The for is needed to ask what the names and scores are. Also, the for is needed to write the scores and names to the file. I get an error when trying to run it saying "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()

in your answer you opened Golf_File with "w" which means write while you want to read the file. To read a file use "r" instead of "w" aka

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()

Im not 100% sure this works because i don't know whats inside of golf.txt but hopefully this could help you. If there are any mistakes be welcome to correct me :). I made some edits like changing a variable name that was wrong and changing "r"(read) to "wr"(write and read). also put the file close after the loop so it would work more than one time. I thought wr was a thing but i was wrong prbly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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