我经常运行以下代码,使用以下代码从Python写入文件:
def function():
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
fifo = open(file, 'w')
if (os.path.isfile(file) and os.access(file, os.W_OK)):
fifo.write("stuff")
fifo.close()
else:
time.sleep(1)
function()
不幸的是,我收到以下错误(并非所有时间):
IOError: [Errno 2] No such file or directory
这是不言自明的,但我不明白为什么所有预防措施都不起作用,例如isfile
或access..W_OK
?如何避免出现此问题?
此外,机器越慢,遇到错误的频率就越低。
答案 0 :(得分:0)
另请参阅“LBYL vs EAFP in Java?”:
您应该采用EAFP方法,而不是检查操作是否正常(LBYL)。做你想做的事,检查它是否正常工作。
此外,最好不要递归调用function()
,如果错误仍然存在,可能会导致堆栈溢出。
更好
def function():
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../my_file')
while True:
try:
with open(file, 'w') as file: # automatically closes...
file.write("some stuff")
except IOError, e:
time.sleep(1)
continue
break # the while loop