gpt4 book ai didi

python - Python 中的 os.open 错误

转载 作者:行者123 更新时间:2023-11-28 19:49:46 24 4
gpt4 key购买 nike

我正在尝试创建并写入一个文件(如果它尚不存在),以便它在竞争条件下是合作安全的,但我遇到了(可能是愚蠢的)问题。首先,这是代码:

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 测试的。如果您尝试代码并且它适合您,请写下您的环境的评论。

也非常欢迎至少同样安全的替代代码。

最佳答案

改变行:

fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666)

改为:

fd=os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)

关于python - Python 中的 os.open 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15791284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com