python close file descriptor question

前端 未结 4 1517
日久生厌
日久生厌 2020-11-28 08:20

I think this question is more of a \"coding style\" rather than technical issue.

Said I have a line of code:

buf = open(\'test.txt\',\'r\').readlines         


        
4条回答
  •  时光取名叫无心
    2020-11-28 08:37

    Usually in CPython, the file is closed right away when the reference count drops to zero (although this behaviour is not guaranteed for future versions of CPython)

    In other implementations, such as Jython, the file won't be closed until it is garbarge collected, which can be a long time later.

    It's poor style to have code that works differently depending on the implementation's behaviour.

    If it's just for a quickie script or something you are trying in the interpreter shell it's good enough, but for any sort of production work you should usually use a context manager as in Falmarri's answer

提交回复
热议问题