Search code examples
pythonio

Is python with block self closing opened resource?


I'm a quite experimented Java developer and I am wondering wether the with block in python is acting the same as a Java embedded try/catch. In the following examples, I'm writing to a random file in python and Java

import io

with io.open("filename", "w") as file:
   file.write("a test")
   #is file.close() necessary here ?
   #file.close()


File file = new File("test.txt");
try(FileWriter writer = new FileWriter(file)) {
    writer.write("a test");
    // here writer.close() is useless as it is auto closed by the try catch block
} catch(IOException e){
    e.printStackTrace();
}

are those 2 block acting exactly the same, or is the python block not closing the resource until program ends ?


Solution

  • (open is a builtin, so you don't need to import io, io.open is simply an alias for open.)

    Using your example behaves as if you did:

    file = open('filename', 'w')
    try:
        file.write("a test")
    finally:
        file.close()
    

    So this means the file is closed automatically, both on success or if an exception is raised.

    For more information on the with statement, I recommend the Python documentation:

    Context managers are really useful and versatile tools, I recommend reading more about them!