打开文件进行读取/写入,如果需要创建 [英] Open file for read/write, create if needed
问题描述
据我所知, open
builtin 似乎不符合任务:它提供了各种模式,但每一个我尝试失败,至少满足我的一个要求:
r +
文件不存在。 w +
会截断文件,丢失任何现有内容。 > a +
会强制所有的写入到文件的最后,至少在我的OS X上。在打开文件之前检查是否存在感觉不好,因为它为比赛条件留下了空间。这同样适用于在异常处理程序中使用不同模式重新打开。我希望有一个更好的办法。
您需要使用 os.open()
可以在< c $ c> open()允许。特别是,传递 os.RDWR | os.O_CREAT
作为 flags
应该做你想做的事情。有关详细信息,请参阅 open(2)
手册页。然后,您可以将返回的FD传递给 os.fdopen()
从中获取文件对象。
What is the most elegant way to open a file such that
- the file gets created if it does not exist,
- the file won't be truncated if it does exist and
- it is possible to write any part of the file (after seeking), not just the end?
As far as I can tell, the open
builtin doesn't seem up to the task: it provides various modes, but every one I tried fails to satisfy at least one of my requirements:
r+
fails if the file does not exist.w+
will truncate the file, losing any existing content.a+
will force all writes to go to the end of the file, at least on my OS X.
Checking for the existence prior to opening the file feels bad since it leaves room for race conditions. The same holds for retrying the open with a different mode from within an exception handler. I hope there is a better way.
You need to use os.open()
to open it at a lower level in the OS than open()
allows. In particular, passing os.RDWR | os.O_CREAT
as flags
should do what you want. See the open(2)
man page for details. You can then pass the returned FD to os.fdopen()
to get a file object from it.
这篇关于打开文件进行读取/写入,如果需要创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!