簡體   English   中英

編寫程序並需要一些輸入

[英]Writing a program and need some input

我正在做一個關於創建一個關於高爾夫的文件的程序,它只允許一個 For. 當我運行程序時,我收到關於 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()

以下將起作用:

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

該文件應該在for循環之外關閉

通常認為使用with語句來處理文件對象更好

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

您可以在有關讀取和寫入文件的 Python 文檔中閱讀有關此內容的更多信息


還有關於官方Python 命名標准的強制性提醒,應避免使用大寫的變量名

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM