Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonで開いているファイルを閉じる方法は?


Pythonで開いているファイルを閉じるには、ファイルのオブジェクトでclose関数を呼び出すだけです。

>>> f = open('hello.txt', 'r')
>>> # Do stuff with file
>>> f.close()

安全ではないので、この方法でファイルを開かないようにしてください。代わりに...openで使用してください。

with open('hello.txt', 'r') as f:
    print(f.read())

withブロックをエスケープすると、ファイルは自動的に閉じます。


  1. Pythonで文字列をファイルにラップするにはどうすればよいですか?

    文字列の内容を含むファイルのようなオブジェクト(Fileと同じダックタイプ)を作成するには、StringIOモジュールを使用できます。文字列をStringIOのコンストラクターに渡すと、オブジェクトのようなファイルとして使用できます。たとえば、 >>> from cStringIO import StringIO >>> f = StringIO('Hello world') >>> f.read() 'Hello world' Python 3では、ioモジュールを使用します。たとえば、 >>

  2. Pythonで例外を処理する方法は?

    Pythonで例外を処理する最も簡単な方法は、「try-except」ブロックを使用することです。 例 try: fob = open("test.txt", "r") fob.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find the file or read data" else: print "Write operation is performed