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
中无法读取任何内容,我不明白,任何想法?
答案 0 :(得分: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)
答案 1 :(得分:3)
在第3行中,f.close应为f.close()
。要强制文件立即写入(而不是在文件关闭时),您可以在写完后调用f.flush()
:有关详细信息,请参阅Why file writing does not happen when it is suppose to happen in the program flow?。
或者,当脚本完全结束时(包括关闭任何交互式解释器窗口,如IDLE),文件将自然关闭。在某些情况下,忘记正确刷新或关闭文件可能会导致极其混乱的行为,例如交互式会话中的错误,如果从命令行运行脚本,则无法看到这些错误。
答案 2 :(得分:1)
f.close只是调用方法对象进行打印而不是调用方法。在REPL中你得到了这个:
f.close
<built-in method close of file object at 0x00000000027B1ED0>
添加方法调用括号。