Python从文件中读取

时间:2015-04-21 21:04:27

标签: python file function

所以我有这个Python代码,我正在开发一个文件并从中读取最大和最小分数百分比,然后显示具有最高分数的团队以及具有最小分数的团队0.75和0.125 我不断收到此错误消息:

ValueError: invalid literal for int() with base 10: '0.75'

感谢您的帮助,谢谢。

这是我正在使用http://www.filedropper.com/nfldata

的文件

这是我的代码:

def create_score_list(nfl_file):
    """Create a list of teams and scores from nfl_file."""
    # 2a create a score list and initialize it to empty
    score_list = []

for line in nfl_file:              # 2b. get each line from the file
    if line[0:28] == 'National Football Conference' or\
             'NFC EAST' in line or\
             'NFC NORTH' in line or\
             'NFC SOUTH' in line or\
             'NFC WEST' in line or\
             'AFC EAST' in line or\
             'AFC NORTH' in line or\
             'AFC SOUTH' in line or\
             'AFC WEST' in line:   
        continue                 # skip header line
    line_list = line.split(',')           # 2bI. csv => split on comma
    # create tuple:
    team_tuple = (int(line_list[4]), line_list[0])
    score_list.append(team_tuple)        # 2bII. append tuple
return score_list

1 个答案:

答案 0 :(得分:0)

这是因为有时line_list[4]float,有时候是string。但是你总是将它解析为int。此外,您需要首先过滤CSV值以跳过标题,现在就这样做:

if line[0:28] == 'National Football Conference' or\
        'American Football Conference' in line or\
        'NFC EAST' in line or\
        'NFC NORTH' in line or\
        'NFC SOUTH' in line or\
        'NFC WEST' in line or\
        'AFC EAST' in line or\
        'AFC NORTH' in line or\
        'AFC SOUTH' in line or\
        'AFC WEST' in line: 

但你错过了一些案例。您可以通过检查line_list[4]中的值是否为float来简化它。

try:
    score = float(line_list[4])
except ValueError:
    continue # The value isn't a float

所以create_score_list(nfl_file)将是:

def create_score_list(nfl_file):
    """Create a list of teams and scores from nfl_file."""
    # 2a create a score list and initialize it to empty
    score_list = []

    for line in nfl_file:              # 2b. get each line from the file
        line_list = line.split(',')           # 2bI. csv => split on comma
        score = None
        try:
            score = float(line_list[4])
        except ValueError:
            continue # The value isn't a float

        # create tuple:
        team_tuple = (score, line_list[0])
        score_list.append(team_tuple)        # 2bII. append tuple
    return score_list