<pre><code>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()
</code></pre>
<p>基本上,您是在读取整个文件,而不是重置指针所在的位置。要么关闭文件,然后重新打开,这将花费更多的精力,要么使用参数<code>0</code>调用<code>seek()</code>函数。你知道吗</p>
<p>基本上,文件的<code>read</code>来源就像键入时文本文件中的光标。现在按住<code>-></code>键,直到到达文件末尾。下一次当您尝试读取某些内容时,如果您没有将光标设置回起始位置,它只会读取<code>end of file</code>符号并认为它是空的。你知道吗</p>
<p><code>seek(0)</code>告诉文件指针或光标(在我们的示例中)返回到开始处。<code>seek()</code>获取一个以字节为单位的参数,以零作为开始。你知道吗</p>