3

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?

4
  • You can try to use "with" contex in python with filelike objects. Commented Jun 21, 2013 at 14:01
  • 4
    A 1 liner could be open(okFilePath, 'w+').close() ? Commented Jun 21, 2013 at 14:08
  • @karthikr Except if open raises an exception, it won't be closed. with open(path, 'w+'): pass can technically be expressed on a single line though, and that will handle exceptions. Commented Jun 21, 2013 at 14:15
  • Note that in python3.3 you can use the 'x' mode for creating a file or failing if it exists already/cannot be created. Commented Jun 22, 2013 at 15:49

5 Answers 5

8

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
Sign up to request clarification or add additional context in comments.

6 Comments

What if I don't want to do anything with the file. I simply want to create it?
@Ben: Then leave the as f part out.
@Ben: ...and change the # Do whatever with f line to just pass or put everything on one line with open(path_to_file, w+): pass.
I only partially agree with this answer because it is NOT a oneliner (okay, the with ...: pass is oneliner). You can do open(path_to_file, "w+").close() which opens (creates if not present) and then closes the file.
@rbaleksandar There is no advantage in writing code in one line. I personally don't understand this desire.
|
3

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

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

Comments

2

The simplest solution would be:

open(fileName, 'w').close()

Comments

2

The mknod function creates a new file without opening it

import os
import stat
os.mknod('test', 0o600 | stat.S_IFREG)
# 0o600 -> owner can read+write file, group and other have no permissions
# stat.S_IFREG -> create regular file, instead of character/block device, pipe, or other special file

Caveat: only available on Unix

Comments

0

If you want a real one liner:

os.remove("echo > YourFile")

It will work on Linux and Windows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.