簡體   English   中英

您如何知道何時在python中關閉文件?

[英]How do you know when to close a file in python?

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)


in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
#above is the original code. 

他關閉了上面的文件。 但是,在常見的學生問題中,就是這樣。

問:當我嘗試使此腳本更短時,當我最后關閉文件時出現錯誤。

答:您可能做了類似的事情,indata = open(from_file).read(),這意味着您到達腳本結尾時無需再執行in_file.close()。 一旦運行一行,它就應該已經被Python關閉。

因此,您如何知道何時關閉文件以及何時不關閉文件?

謝謝大家,我明白了! :)

文件對象方法開始

在處理文件對象時,最好使用with關鍵字。 這樣做的好處是,即使在執行過程中引發了異常,文件在其套件完成后也將正確關閉。 它也比編寫等效的try-finally塊要短得多:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

什么時候關閉文件? 總是-完成工作后。 否則只會占用內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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