当前位置: 动力学知识库 > 问答 > 编程问答 >

Closing file in Python without having an explicit variable associated with it

问题描述:

I am new to python. Somebody help me please.

I have opened a file like this

files = {'file' : open(jsonfile, 'r')}

How to close the file?

网友答案:

It would be better if you do introspection before closing the file by checking its type.

>>> files = {'file_1': open('abc.txt', 'w')}
>>> if isinstance(files.get('file_1'), file):
...     files.get('file_1').close()
... 
>>> files.get('file_1')
<closed file 'abc.txt', mode 'w' at 0x90f16a8>
网友答案:

Try:

   f = open(jsonfile, 'r')
   files = {'file' : f}
   f.close()
分享给朋友:
您可能感兴趣的文章:
随机阅读: