2017-10-09 114 views
0

我对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 = points_earned // 3 
    ties = points_earned % 3 
    losses = 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 
    output_file.write() 

# -------------------------------------- 

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) 

但我发现了一个错误,指出
文件 “C:\用户”,第12行,在process_season 胜= points_earned // 3 TypeError:不支持的操作数类型为//:'str'和'int'

任何帮助,将不胜感激谢谢。

+1

当您从文件中读取某些内容时,将会有一个'str'类型。只要把'int(points_earned)// 3'放在那里,只要'points_earned'是一个整数就可以了。 – Unni

回答

1

您试图分割一个字符串。

process_season()您可以尝试铸造season[0]season[1]作为整数。

process_season(output_file, season_number, int(season[0]), int(season[1])) 
+0

完美。谢谢! –