Search code examples
pythonioioerror

Python and files (IO)opening and closing


I ask about syntax writing in python. if i have 2 files that i want to open and i make exception like this:

try:
    f = open(...)
    ...
    f.close()
    f.open(...) #opens file too
    f.close()
except IOError:
    print("Error with opening file")
finnaly:
    f.close()

Is this correct syntax ?


Solution

  • File has no .open method that I'm aware

    The idiomatic way is using with

    with open(...) as f1, open(...) as f2:
           ...
    

    You can then surround it by try catch as needed. It will close the files at end of with block.