[英]python - creating an empty file and closing in one line
我想确保正确清理所有资源。 这样做是否安全:
try:
closing(open(okFilePath, "w"))
except Exception, exception:
logger.error(exception)
raise
编辑:
事实上,考虑一下,我什至需要 try/catch ,因为我无论如何都可以在更高级别登录时引发异常。 如果在创建文件时出错,可以假设没有什么可以关闭吗?
要确保在任何情况下都关闭文件,您可以使用with语句。 例如:
try:
with open(path_to_file, "w+") as f:
# Do whatever with f
except:
# log exception
您可以使用它来创建一个文件并在一行中关闭它。
with open(file_path, 'w') as document: pass
如果你想要一个真正的一个班轮:
os.remove("echo > YourFile")
它适用于 Linux 和 Windows。
最简单的解决方案是:
open(fileName, 'w').close()
mknod
函数创建一个新文件而不打开它
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
警告:仅在 Unix 上可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.