如果文件尚不存在,我正在尝试创建和写入文件,以便在竞争条件下合作安全,并且我遇到了(可能是愚蠢的)问题。首先,这是代码:
import os
def safewrite(text, filename):
print "Going to open", filename
fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666) ##### problem line?
print "Going to write after opening fd", fd
os.write(fd, text)
print "Going to close after writing", text
os.close(fd)
print "Going to return after closing"
#test code to verify file writing works otherwise
f = open("foo2.txt", "w")
f.write("foo\n");
f.close()
f = open("foo2.txt", "r")
print "First write contents:", f.read()
f.close()
os.remove("foo2.txt")
#call the problem method
safewrite ("test\n", "foo2.txt")
然后问题,我得到异常:
First write contents: foo
Going to open foo2.txt
Going to write after opening fd 5
Traceback (most recent call last):
File "/home/user/test.py", line 21, in <module>
safewrite ("test\n", "foo2.txt")
File "/home/user/test.py", line 7, in safewrite
os.write(fd, text)
OSError: [Errno 9] Bad file descriptor
上面的代码中标记了可能的问题行(我的意思是,它还能是什么?),但我不知道如何解决它。问题是什么?
注意:以上是在 Linux VM 中使用 Python 2.7.3 进行测试的。如果您尝试该代码并且它适用于您,请在您的环境中写下评论。
至少安全地做同样事情的替代代码也是非常受欢迎的。