2
f = open('day_temps.txt','w')
f.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")
f.close

def get_stats(file_name):
    temp_file = open(file_name,'r')
    temp_array = temp_file.read().split(',')
    number_array = []
    for value in temp_array:
        number_array.append(float(value))
    number_array.sort()
    max_value = number_array[-1]
    min_value = number_array[0]
    sum_value = 0
    for value in number_array:
        sum_value += value
    avg_value = sum_value / len(number_array)
    return min_value, max_value, avg_value

mini, maxi, mean = get_stats('day_temps.txt')
print "({0:.5}, {1:.5}, {2:.5})".format(mini, maxi, mean)

没有first 3 line,代码可以工作,有了它,我什么都看不懂temp_file,我不明白,知道吗?

4

3 回答 3

6

你从来没有用这行代码关闭文件:

f.close

使用f.close()with语法,它会自动关闭文件句柄并防止出现这样的问题:

with open('day_temps.txt', 'w') as handle:
    handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")

此外,您可以显着压缩代码:

with open('day_temps.txt', 'w') as handle:
    handle.write("10.3,10.1,9.9,9.9,9.8,9.6,9.0,10.1,10.2,11.1")

def get_stats(file_name):
    with open(file_name, 'r') as handle:
        numbers = map(float, handle.read().split(','))

    return min(numbers), max(numbers), sum(numbers) / len(numbers)

if __name__ == '__main__':
    stats = get_stats('day_temps.txt')
    print "({0:.5}, {1:.5}, {2:.5})".format(*stats)
于 2012-09-14T03:31:11.020 回答
3

在第 3 行, f.close 应该是f.close(). 要强制文件立即写入(而不是在文件关闭时),您可以f.flush()在写入后调用:请参阅为什么在程序流程中假设文件写入不会发生?更多细节。

或者,当脚本完全结束时文件将自然关闭(包括关闭任何交互式解释器窗口,如 IDLE)。在某些情况下,忘记正确刷新或关闭文件可能会导致极其混乱的行为,例如从命令行运行脚本时看不到的交互式会话中的错误。

于 2012-09-14T03:30:47.727 回答
1

f.close 只是调用方法对象进行打印而不是调用方法。在 REPL 中你会得到:

f.close
<built-in method close of file object at 0x00000000027B1ED0>

添加您的方法调用括号。

于 2012-09-14T04:08:10.203 回答