0

ファイルはいつ閉じられますか?

    # Read all data from input file
    mergeData = open( "myinput.txt","r" )
    allData = mergeData.read()
    mergeData.close()

このコードを代用できますか?

allData = read.open( "myinput.txt","r" )

ファイルがいつ閉じられるのだろうかと思っていましたか?ステートメントが実行されると閉じられますか?または、プログラムが終了するまで待ちます。

4

2 に答える 2

5

CPython closes a file object automatically when the object is deleted; it is deleted when it's reference count drops to zero (no more variables refer to it). So if you use mergeData in a function, as soon as the function is done, the local variables are cleaned up and the file is closed.

If you use allData = open( "myinput.txt","r" ).read() the reference count drops to 0 the moment .read() returns, and on CPython that means the file is closed there and then.

On other implementations such as Jython or IronPython, where object lifetime is managed differently, the moment an object is actually deleted could be much later.

The best way to use a file though, is as a context manager:

with open( "myinput.txt","r" ) as mergeData:
    allData = mergeData.read()

which calls .close() on mergeData automatically. See the file.open() documentation and the documentation for the with statement.

于 2013-02-26T21:11:47.460 に答える
2

はい。はい、できます。メモリリークなどはありません。

fileによって返されたオブジェクトopen()がスコープ外に出てガベージ コレクションが行われると、ファイル ハンドルはすぐに閉じられます。

あなたが好むなら、あなたは次のようなことをしたいかもしれません:

with open('myinput.txt') as f:
    data = f.read()

これにより、作業が完了するとすぐにファイルが閉じられます。

于 2013-02-26T21:12:25.833 に答える