pythonpython-3.xwith-statementpathlib

How to close files using the pathlib module?


Historically I have always used the following for reading files in python:

with open("file", "r") as f:
    for line in f:
        # do thing to line

Is this still the recommend approach? Are there any drawbacks to using the following:

from pathlib import Path

path = Path("file")
for line in path.open():
    # do thing to line

Most of the references I found are using the with keyword for opening files for the convenience of not having to explicitly close the file. Is this applicable for the iterator approach here?

with open() docs


Solution

  • If all you wanted to do was read or write a small blob of text (or bytes), then you no longer need to use a with-statement when using pathlib:

    >>> import pathlib
    >>> path = pathlib.Path("/tmp/example.txt")
    >>> path.write_text("hello world")
    11
    >>> path.read_text()
    'hello world'
    >>> path.read_bytes()
    b'hello world'
    

    These methods still use a context-manager internally (src).

    Opening a large file to iterate lines should still use a with-statement, as the docs show:

    >>> with path.open() as f:
    ...     for line in f:
    ...         print(line)
    ...
    hello world