Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.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:函数调用一次后,如果我再次调用,它将打印0_Python_Python 3.x - Fatal编程技术网

Python:函数调用一次后,如果我再次调用,它将打印0

Python:函数调用一次后,如果我再次调用,它将打印0,python,python-3.x,Python,Python 3.x,我试图在文本中进行数据挖掘,但在调用data_mining函数一次后,下次调用它时,它将仅返回0。我试图通过写入text_file2=text_file[:]来复制text_file,但它返回了一个错误 def data_mining (text_file, start, end): count = 0 total_value = 0 average = 0 for file_line_number, line in enumerate(text_file):

我试图在文本中进行数据挖掘,但在调用data_mining函数一次后,下次调用它时,它将仅返回0。我试图通过写入text_file2=text_file[:]来复制text_file,但它返回了一个错误

def data_mining (text_file, start, end):
    count = 0
    total_value = 0
    average = 0
    for file_line_number, line in enumerate(text_file):
        if (file_line_number % 2) == 0:
            value = line[start:end]
            value = int(value)
            total_value += value
            count += 1
    return total_value, count


def main ():
    #Main program.
    text_file = open("93cars.dat.txt", "r")

    city_mpg = data_mining(text_file, 52, 54)
    highway_mpg = data_mining(text_file, 55, 57)
    midrange_price = data_mining(text_file, 42, 44)

    print (city_mpg)
    print (highway_mpg)
    print (midrange_price)

main()  
基本上,您正在读取整个文件,而不是重置指针所在的位置。关闭文件并重新打开(这将花费更多的精力),或者使用参数
0
调用
seek()
函数

基本上,文件的读取方式就像键入时文本文件中的光标一样。现在按住
->
键,直到文件结束。下次尝试读取某个内容时,如果您没有将光标设置回起始位置,它只会读取文件结尾的
符号,并认为它是空的


seek(0)
告诉文件指针或光标(来自我们的示例)返回开始
seek()
将以字节为单位的参数转到该文件的字节,零作为开始

第一次调用
data\u mining()
文件被读取,文件读取指针结束在文件的末尾。在
data\u mining
的开头调用
text\u file.seek(0)
,将确保指针始终从文件的开头开始

def data_mining (text_file, start, end):
    count = 0
    total_value = 0
    average = 0
    for file_line_number, line in enumerate(text_file):
        if (file_line_number % 2) == 0:
            value = line[start:end]
            value = int(value)
            total_value += value
            count += 1
    return total_value, count


def main ():
    #Main program.
    text_file = open("93cars.dat.txt", "r")
    city_mpg = data_mining(text_file, 52, 54)
    text_file.seek(0) #reset the file pointer to 0
    highway_mpg = data_mining(text_file, 55, 57)
    text_file.seek(0) #reset the file pointer to 0
    midrange_price = data_mining(text_file, 42, 44)

    print (city_mpg)
    print (highway_mpg)
    print (midrange_price)

main()