1

I am doing a program about creating a file about golf, it allows only one For. When I run the program I get an error about Golf_File.write(Name + ("\n") ValueError: I/O operation on closed file.

Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')

for count in range(1,Num_People+1):
    Name = input("Enter the player's name: ")
    Score = int(input("Enter the player's score: "))
    Golf_File.write(Name + ("\n"))
    Golf_File.write(str(Score) + ("\n"))

    Golf_File.close()

2 Answers 2

1

The following will work:

Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')

for count in range(1,Num_People+1):
    Name = input("Enter the player's name: ")
    Score = int(input("Enter the player's score: "))
    Golf_File.write(Name + ("\n"))
    Golf_File.write(str(Score) + ("\n"))

Golf_File.close()

The file should be closed outside the for loop

Sign up to request clarification or add additional context in comments.

Comments

0

It is generally considered better to use with statements to handle file objects

Num_People = int(input("How many golfers are playing?: "))

with open('golf.txt', 'w') as Golf_File:
    for count in range(1,Num_People+1):
        Name = input("Enter the player's name: ")
        Score = int(input("Enter the player's score: "))
        Golf_File.write(Name + ("\n"))
        Golf_File.write(str(Score) + ("\n"))

You can read more about this in the Python documentation about reading and writing files


Also obligatory reminder about the official Python naming standards, capitalized variable names should be avoided

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.