diff --git a/files.html b/files.html index 4979725..4039639 100644 --- a/files.html +++ b/files.html @@ -201,9 +201,20 @@ ValueError: I/O operation on closed file.
  • Closed file objects do have one useful attribute: the closed attribute will confirm that the file is closed. -

    Using The with Statement

    +

    Closing Files Automatically

    -

    FIXME "with open(...) as file" pattern +

    File objects have an explicit close() method, but what happens if your code has a bug and crashes before you call close()? That file could theoretically stay open for much longer than necessary. While you’re debugging on your local computer, that’s not a big deal. On a production server, maybe it is. + +

    Python 2 had a solution for this: the try..finally block. That still works in Python 3, and you may see it in other people’s code or in older code that was ported to Python 3. But Python 3 also adds a cleaner solution: the with statement. + +

    with open('examples/chinese.txt', encoding='utf-8') as a_file:
    +    a_file.seek(17)
    +    a_character = a_file.read(1)
    +    print(a_character)
    + +

    This code calls open(), but it never calls a_file.close(). The with statement starts a code block, like an if statement or a for loop. Inside this code block, you can use the variable a_file as the file object returned from the call to open(). All the regular file object methods are available — seek(), read(), whatever you need. When the with block ends, Python calls a_file.close() method automatically. + +

    FIXME other with examples

    Reading Data One Line At A Time