0

I am stuck in an "error" during my folder creation. First of all, this is the code I am using:

import os
import errno
import subprocess

try:
    folder = os.makedirs(os.path.expanduser('~\\Desktop\\FOLDER'))
except OSError as e:
    if e.errno != errno.EEXIST:
        raise
print(os.path.isdir('~\\Desktop\\FOLDER'), '- FOLDER CREATED')

So, the code do the following:

  • using os.makedirs() it creates a new folder on Desktop. I want to create a folder which use cross-platform path, so I am using ~ symbol

  • using print() I want to verify that the folder really exist, that the directory is real. The output of this is True or False.

The problem is: if I am using the ~ symbol in print(), the output is False. If I put the complete path to the folder (ex: os.path.isdir('C:\\Users\\Bob\\Desktop\\FOLDER'), the output is True.

Why does this happen ? The folder is really created even if I have a False output ?

lucians
  • 2,239
  • 5
  • 36
  • 64
  • 1
    https://stackoverflow.com/questions/7403918/cross-platform-desktop-directory-path – Harry Oct 02 '17 at 09:12
  • It'd be better if you just created a variable to store the expanded path and use that where necessary: `path = os.path.expanduser('~\\Desktop\\Folder')`. Then use `path` as the argument to `os.makedirs()` and `os.path.isdir()`. This help reduce errors such as this one. – John Szakmeister Oct 02 '17 at 09:16
  • I tried doing that but it gives me an error...Will try again just now. Thanks BTW. Also, the problem is that I have some nested folders, more complex than just one with (concatenad) variables in path. – lucians Oct 02 '17 at 09:17

1 Answers1

2

You are just missing the expanduser method when calling isdir:

print(os.path.isdir(os.path.expanduser('~\\Desktop\\FOLDER')), '- FOLDER CREATED')

You don't really need the check at the end as well. Since if there is no exception, you can be sure that the creation is successful.

Here is a cleaner implementation:

try:
    dirpath = os.path.expanduser('~\\Desktop\\FOLDER')
    os.makedirs(dirpath)
    print dirpath, "creation successful"
except OSError as e:
    print dirpath, "creation failed"
    if e.errno != errno.EEXIST:
        raise
Daniel Trugman
  • 8,186
  • 20
  • 41