簡體   English   中英

當我打開要首先寫入的文件時,為什么在File.open中無法讀取任何內容?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM