Reputation: 55
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()
Upvotes: 1
Views: 77
Reputation: 8395
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
Upvotes: 0
Reputation: 8521
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
Upvotes: 1