0

I think I am pretty familiar with how os.mkdir and os.makedirs work but somehow I'm missing something here. I have a function named check_for_dir() in my script myscript.py that is located in this path Users/myuser/Projects/myProject/myscript.py. I want to create a directory named mydirectory in my home folder. It looks like this:

import os

path = 'Users/myuser/mydirectory/'

def check_for_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

check_for_dir(path)

But for some reason the whole structure defined in variable path is created in script's location. What this means is that directory mydirectory/ is created in this path: Users/myuser/Projects/myproject/Users/myuser/mydirectory/

What am I doing wrong?

1 Answer 1

3
import os

path = '/Users/myuser/mydirectory/'

def check_for_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

check_for_dir(path)

I think you have to change path as path = '/Users/myuser/mydirectory/' Hope this will help

If you specify path = 'Users/myuser/mydirectory/' then it will be consider as a relative path then creates a folder as you have mentioned in the question

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I don't follow. Could you explain more in detail?
Oh I'm sorry. I scanned your answer quickly and didn't notice the absence of backlash. Thanks for that.

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.