1

I am trying to create a folder named ~/.Trash (its a hidden directory) without using FileExistsError. I want to create the directory without raising an error.

try:
  os.mkdir('~/.Trash')
except OSError as ex:
  if ex.errno == errno.EEXIST:
    print '' #I leave it blank
  else:
    raise

But I am getting the following error:

OSError: [Error 2] No such file or directory '~/.Trash' 

How can I create a directory protecting against FileExistsError?

Gworld
  • 91
  • 9

1 Answers1

2

The problem is that the tilde (~) does not get expanded to the home directory in Python like it does in Bash. So you're trying to create a directory .Trash under the (non-existent) directory ~. You can use os.path.expanduser(path) if you need a path relative to the home directory.

try:
    os.mkdir(os.path.expanduser('~/.Trash'))
except OSError as e:
    if e.errno != os.errno.EEXIST:
        raise
davidism
  • 98,508
  • 22
  • 317
  • 288