Use of Python constructs when possible to help context managers to properly manage resources.
We can improve the performance (and reduce code) with the with Statement and Context Managers when files are being managed.
Currently, close() is called on every file opened, and some times the file is in a function that may raise an exception or has multiple return paths, using for this try...except.
We could use 'with' statement that clarifies code that previously would use try...finally blocks to ensure all resources we use are properly cleaned up, regardless of if the code returns or an exception is thrown: context managers.
# old file exists, check if same content fl = open(fname, 'r') try: old_data = fl.read() finally: fl.close()
We could do :
with open(fname,'r') as fl fd.read()
and not needed to close the files and the block is calling it automatically.
To DO: Review the code and do the replacement where this case is satisfied.
Note: It works with open(). But not with os.open() as it is just a wrapper for the lower-level POSIX syscall. It returns the file descriptor (a number) that represents the opened file and not a file object: so we cannot use it in this case.