Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用无效的文本函数修复错误_Python - Fatal编程技术网

Python 如何使用无效的文本函数修复错误

Python 如何使用无效的文本函数修复错误,python,Python,我运行代码时遇到问题。基数为10的int的文本无效:“r”。这与我的文件打开功能有关吗?因为以前,我把file_open函数的内容放在read_data函数中。但当我把它自己的函数文件打开时,它就给了我这个错误 def get_filename(): """Return the name of the student data file to be processed""" return "rainfalls2011.csv" def file_open(filename):

我运行代码时遇到问题。基数为10的int的文本无效:“r”。这与我的文件打开功能有关吗?因为以前,我把file_open函数的内容放在read_data函数中。但当我把它自己的函数文件打开时,它就给了我这个错误


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您没有在任何地方调用文件打开函数

2即使它被调用,您也不会从中返回任何内容。它只是声明一个局部变量并退出

3您正在传递文件名以读取_数据-这需要文件中的行,但它得到的是rainfalls2011.csv

4当您迭代文件名时,它会给出字符串“rainfalls2011.csv”中的每个字符。所以在第一次迭代中,您的行是'r'

5 int'r'无效-它将抛出您看到的异常

修正:

使您的文件\u打开函数返回数据 调用文件\u open并将其返回值传递给读取\u数据 您从不调用file_open,只需传递文件名来读取_数据
def file_open(filename):
    with open(filename, "r") as datafile:
        return datafile.readlines() 
def main():
    """The main function"""
    filename = get_filename()
    data = read_data(file_open(filename))
    print_month_totals(data)