Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - creating an empty file and closing in one line

Tags:

python

file-io

I want to ensure that all resources are being cleaned correctly. Is this a safe thing to do:

try:
    closing(open(okFilePath, "w"))
except Exception, exception:
    logger.error(exception)
    raise

EDIT:

Infact, thinking about it, do I even need the try/catch as I am raising the exception anyways I can log at a higher level. If it errors on creating the file, one can assume there is nothing to close?

like image 818
Cheetah Avatar asked May 14 '26 04:05

Cheetah


2 Answers

To be sure that the file is closed in any case, you can use the with statement. For example:

try:
    with open(path_to_file, "w+") as f:
        # Do whatever with f
except:
    # log exception
like image 179
dablak Avatar answered May 16 '26 17:05

dablak


you can use this to just create a file and close it in one line.

with open(file_path, 'w') as document: pass

like image 38
allenite Avatar answered May 16 '26 18:05

allenite