Link Link - 3 years ago 189
Python Question

Error when verifying folder creation (Python)

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 ?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download