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 ?

3
  • 1
    stackoverflow.com/questions/7403918/… Commented Oct 2, 2017 at 9: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. Commented Oct 2, 2017 at 9: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. Commented Oct 2, 2017 at 9:17

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.