[英]Why I can't read anything with File.open in python when I open the file to write first?
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)
没有temp_file
first 3 line
,代码可以工作,有了它,我无法在temp_file
读取任何内容,我不明白,知道吗?
您永远不会使用以下代码关闭文件:
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)
在第3行中,f.close应该读为f.close()
。 要强制文件立即写入(而不是在文件关闭时),可以在写入后调用f.flush()
:请参阅为什么在程序流中假设没有发生文件写入的情况? 更多细节。
或者,当脚本完全结束时(包括关闭所有交互式解释器窗口,例如IDLE),文件将自然关闭。 在某些情况下,忘记正确刷新或关闭文件会导致极为混乱的行为,例如,如果从命令行运行脚本,则无法看到交互式会话中的错误。
f.close只是调用要打印的方法对象,而不是调用方法。在REPL中,您将获得以下信息:
f.close
<built-in method close of file object at 0x00000000027B1ED0>
添加方法调用括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.