2017-01-12 17 views
0

私は、ファイルを開いた回数を忘れてしまったが、私は、少なくとも2倍開いているファイルを閉じる?

私はゼッドA.ショーは、Pythonザ・学ぶ、次のよ

それを開いた後、私はtxt.closeとtxt_again.closeを追加し、それらをクローズする必要があります

with open(my_file) as f: 
    # do something on file object `f` 

明示的にクローズを心配する必要はありません。この方法は:ハード・ウェイ

#imports argv library from system package 
from sys import argv 
    #sets Variable name/how you will access it 
script, filename = argv 
    #opens the given file from the terminal 
txt = open(filename) 
    #prints out the file name that was given in the terminal 
print "Here's your file %r:" % filename 
    #prints out the text from the given file 
print txt.read() 
txt.close() 
#prefered method 
    #you input which file you want to open and read 
print "Type the filename again:" 
    #gets the name of the file from the user 
file_again = raw_input("> ") 
    #opens the file given by the user 
txt_again = open(file_again) 
    #prints the file given by the user 
print txt_again.read() 
txt_again.close() 

答えて

4

ようなことを防止するために、常にのようなコンテキストマネージャwithを使用してファイルを開くことをお勧めします。

利点:

  1. with以内に発生した例外の場合には、Pythonはファイルを閉じるの世話をします。
  2. close()を明示的に言及する必要はありません。
  3. 開いているファイルのスコープ/使用方法を知ることで、はるかに読みやすくなります。

参照:PEP 343 -- The "with" Statement詳細については、Trying to understand python with statement and context managersをチェックしてください。

関連する問題