如何使用无效的文字修复错误-函数

时间:2019-05-08 03:30:00

标签: python

运行代码时遇到问题。 “以10为底的int()的无效文字:'r'”。与我的file_open函数有关吗?因为之前,我实际上在read_data函数内部拥有了file_open函数的内容。但是,一旦我给它提供了自己的功能(file_open),它就会给我这个错误。


def get_filename():
    """Return the name of the student data file to be processed"""
    return "rainfalls2011.csv"

def file_open(filename):
    with open(filename, "r") as datafile:
        data = datafile.readlines()    

def read_data(data):


    results, total_rainfall = [], 0  
    for line in data:
        columns = line.split(',')
        month, num_days = int(columns[0]), int(columns[1])


        total_rainfall = sum([float(col) for col in columns[2:2 + num_days]])
        results.append((month, total_rainfall))


    return results


def print_month_totals(results):
    """Process the given csv file of rainfall data and print the
       monthly rainfall totals. input_csv_filename is the name of
       the input file, which is assumed to have the month number in
       column 1, the number of days in the month in column 2 and the
       floating point rainfalls (in mm) for each month in the remaining
       columns of the row.
    """

    print('Total rainfalls for each month')
    for (month, total_rainfall) in results:
        print('Month {:2}: {:.1f}'.format(month, total_rainfall))



def main():
    """The main function"""
    filename = get_filename()
    data = read_data(filename)
    print_month_totals(data)


main()```

1 个答案:

答案 0 :(得分:1)

1)您不会在任何地方调用file_open函数。

2)即使它被调用,也不会从它返回任何东西。它只是声明一个局部变量然后退出。

3)您正在将filename传递到read_data-期望从文件中获取行,但是却得到rainfalls2011.csv

4)遍历文件名时,它将为您提供字符串“ rainfalls2011.csv”中的每个字符。因此,在第一次迭代中,您将line作为'r'。

5)int('r')无效-它将引发您所看到的异常。

修复:

  • 使您file_open函数返回数据
def file_open(filename):
    with open(filename, "r") as datafile:
        return datafile.readlines() 
  • 调用file_open并将其返回值传递给read_data
def main():
    """The main function"""
    filename = get_filename()
    data = read_data(file_open(filename))
    print_month_totals(data)