我對Python比較陌生,正在處理輸入和輸出文件。這裏是輸入文件:(Python初學者)我的代碼中輸出文件爲空
1 3
1 1
1 0
20 30
,這裏是我的代碼,將其作爲「soccer_in.txt」,並假設輸出以下爲「soccer_out.txt」:使用該
Season: 1, Games Played: 1, Points earned: 3
Possible Win-Tie-Loss Records
-----------------------------
1-0-0
Season: 2, Games Played: 1, Points earned: 1
Possible Win-Tie-Loss Records
-----------------------------
0-1-0
Season: 3, Games Played: 1, Points earned: 0
Possible Win-Tie-Loss Records
-----------------------------
0-0-1
Season: 4, Games Played: 20, Points earned: 30
Possible Win-Tie-Loss Records
-----------------------------
10-0-10
9-3-8
8-6-6
7-9-4
6-12-2
5-15-0
代碼:
def process_season(output_file, season, games_played, points_earned):
output_file.write("Season: " + str(season) + ", Games Played: " + str(games_played) +
", Points earned: " + str(points_earned))
output_file.write("Possible Win-Tie-Loss Records")
output_file.write("-----------------------------")
wins = int(points_earned) // 3
ties = int(points_earned) % 3
losses = int(games_played) - wins - ties
while (wins >= 0) and (losses >= 0):
output_file.write(str(wins) + "-" + str(ties) + "-" + str(losses))
wins -= 1
ties += 3
losses -= 2
# --------------------------------------
def process_seasons(input_file, output_file):
season_number = 0
for season in input_file:
season_number += 1
process_season(output_file, season_number, season[0], season[1])
# --------------------------------------
f_in=open("soccer-in.txt", "r")
f_out=open("soccer-out.txt", "w+")
process_seasons(f_in, f_out)
我沒有得到任何錯誤,但我的輸出文件是空的,當我運行我的代碼。我不確定發生了什麼事情,任何幫助將不勝感激。 謝謝!
編輯:到目前爲止,所提出的解決方案都沒有工作。我運行該文件,「soccer-output.txt」仍然是空白。我看到關閉文件的問題,但這並沒有解決輸出文件爲空的事實。
編輯2:NEVERMIND!我在我的電腦上打開了輸入文件,該文件不允許代碼工作。謝謝大家
把'output_file.close()'放在'process_season()'函數的末尾,看它是否有效。 – Unni
你在哪裏關閉輸出文件? – toonarmycaptain
你不需要關閉文件。 垃圾回收期間,Python將爲您關閉文件。 這不是錯誤的原因。 – 0TTT0