简体   繁体   中英

python - creating an empty file and closing in one line

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?

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

您可以使用它来创建一个文件并在一行中关闭它。

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

If you want a real one liner:

os.remove("echo > YourFile")

It will work on Linux and Windows.

最简单的解决方案是:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM