Is there a need to close files that have no reference to them?

前端 未结 6 609
遥遥无期
遥遥无期 2020-12-08 09:03

As a complete beginner to programming, I am trying to understand the basic concepts of opening and closing files. One exercise I am doing is creating a script that allows me

6条回答
  •  难免孤独
    2020-12-08 09:51

    It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

    >>> with open('workfile', 'r') as f:
    ...     read_data = f.read()
    >>> f.closed
    True
    

提交回复
热议问题