Python 2.6 File exists errno 17,

2019-04-12 07:13发布

If a file already exists how do I get rid of the error 17 and make a warning message instead?

import os, sys

# Path to be created
path = "/tmp/home/monthly/daily"

try:
   os.makedirs(path)
except OSError as e:
  if e.errno == 17:
     //do something

os.makedirs( path, 0755 );

print "Path is created"

However it still shows the ERRNO 17 message. What can I do?

3条回答
闹够了就滚
2楼-- · 2019-04-12 07:51

After the first call to the os.makedirs the directory will be created. (or no change if the directory was already there)

The second call will always raise the exception.

Remove the second call to the makedirs:

try:
    os.makedirs(path, 0755)
except OSError as e:
    if e.errno == 17:  # errno.EEXIST
        os.chmod(path, 0755)

# os.makedirs( path, 0755 )  <----
查看更多
做个烂人
3楼-- · 2019-04-12 07:57

You can create a variable to see if you created the file successfully like this:

import os, sys

# Path to be created
path = "/tmp/home/monthly/daily"

created = False
is_error_17 = False

try:
   os.makedirs(path)
   created = True
except OSError as e:
  if e.errno == 17:
     print 'File has benn created before'
     is_error_17 = True
     pass

if created == True:
   print 'created file successfully'
else:
   print 'created file failed.'
   if is_error_17 == True:
      print 'you got error 17' 

In your code if first try catch the error, the second os.makedirs( path, 0755 ); will still raise the error again.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-12 08:01

I think does what you want. When an OSError error occurs, it checks the error code and prints a warning message if it the one you're interested in handling, otherwise it just propagates the exception. Note the use the optional mode argument to os.makedirs() which overrides the default of 0777.

import errno, os, sys

# Path to be created
path = "/tmp/home/monthly/daily"

try:
    os.makedirs(path, 0755)
except OSError as e:
    if e.error == errno.EEXIST:  # file exists error?
        print 'warning: {} exists'.format(path)
    else:
        raise  # re-raise the exception

# make sure its mode is right
os.chmod(path, 0755)

print "Path existed or was created"
查看更多
登录 后发表回答