python在指定目录创建文件失败_Python“FileExists”制作目录时出错

在多线程环境中,Python脚本尝试在指定目录mydir创建文件时遇到'FileExists'错误。这可能是由于线程间的race条件导致的,即一个线程在另一个线程完成创建目录之前进行了创建。为了解决这个问题,可以使用异常处理,尝试创建目录并捕获'EEXIST'错误,避免重复创建。如果多线程大量尝试创建预定义的目录系列,这种方法可能会引发频繁的异常,此时最好只用一个线程来创建目录。
摘要由CSDN通过智能技术生成

I have several threads running in parallel from Python on a cluster system. Each python thread outputs to a directory mydir. Each script, before outputting checks if mydir exists and if not creates it:

if not os.path.isdir(mydir):

os.makedirs(mydir)

but this yields the error:

os.makedirs(self.log_dir)

File "/usr/lib/python2.6/os.py", line 157, in makedirs

mkdir(name,mode)

OSError: [Errno 17] File exists

I suspect it might be due to a race condition, where one job creates the dir before the other gets to it. Is this possible? If so, how can this error be avoided?

I'm not sure it's a race condition so was wondering if other issues in Python can cause this odd error.

解决方案

Any time code can execute between when you check something and when you act on it, you will have a race condition. One way to

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值