1

I made a function in Python (WinOS) that ends up creating new directories (where future work is stored). So at some point, I define the directories and after I use os.mkdir(os.pahth.join('current_dir', 'new_dir1', 'new_dir2')). And it works.

The problem is that this same function is not working on Linux OS (Ubuntu). In Linux I can only generate a single directory. I.e.:

os.mkdir(os.path.join('current_dir', 'new_dir1', 'new_dir2')) returns error :

(OSError: [Errno 2] No such file or directory: '/[current_dir]/new_dir1/new_dir2')

but:

os.mkdir(os.path.join('current_dir', 'new_dir1')) - This works, returns the single directory

but I need to create 2 directories in Linux, not one...

I have tried several "easy combos" such as

new_dirs = os.path.join('new_dir1', 'new_dir2')
os.mkdir(os.path.join('current_dir', new_dirs)

returns the same error:

OSError: [Errno 2] No such file or directory: '/[current_dir]/new_dir1/new_dir2'

What I do (and works in Linux) is the next:

#Generate the path for the output files
working_path = os.path.join(outfile_path, 'First_Corregistration', 'Split_Area', '') 
#Verify is the path exist, if not, create it.
if not os.path.exists(working_path):
    os.mkdir(working_path)

Can somebody tell me how to create 2 or more new directories (one inside the other) with Linux. I highlight again what is more weird: My current solution works with Windows, but not with Linux.

3
  • seems like a job for... os.makedirs (not os.makedir), try, see if it works. reference - docs.python.org/3/library/os.html#os.mkdirs Commented Sep 12, 2019 at 13:31
  • Yes! It works, it makes the job! It is interesting because Windows works without this function. Commented Sep 12, 2019 at 13:37
  • yes this is actually interesting, i'll try to find why and if i will find i will add it to my answer. don't forget to mark the correct answer if it is solved :) Commented Sep 12, 2019 at 13:37

1 Answer 1

3

instead of os.mkdir use os.makedirs, should work. simple example:

os.makedirs("brand/new/directory")

should create the directories: brand, new and directory

from https://docs.python.org/3/library/os.html#os.mkdirs :

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.

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.