Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a folder if it doesn't already exist

I've run into a few cases with WordPress installs with Bluehost where I've encountered errors with my WordPress theme because the uploads folder wp-content/uploads was not present.

Apparently the Bluehost cPanel WordPress installer does not create this folder, though HostGator does.

So I need to add code to my theme that checks for the folder and creates it otherwise.

like image 719
Scott B Avatar asked Feb 20 '10 19:02

Scott B


People also ask

How do you create a directory if it does not exist?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.

How do you mkdir only if a DIR does not already exist?

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

What does mkdir do if it already exists?

mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.

How do you create a folder in Python if it does not exist?

import os path = '/Users/krunal/Desktop/code/database' os. makedirs(path, exist_ok=False) print("The new directory is created!") So that's how you easily create directories and subdirectories in Python with makedirs(). That's it for creating a directory if not exist in Python.


2 Answers

Try this, using mkdir:

if (!file_exists('path/to/directory')) {     mkdir('path/to/directory', 0777, true); } 

Note that 0777 is already the default mode for directories and may still be modified by the current umask.

like image 179
Gumbo Avatar answered Sep 30 '22 02:09

Gumbo


Here is the missing piece. You need to pass 'recursive' flag as third argument (boolean true) in mkdir call like this:

mkdir('path/to/directory', 0755, true); 
like image 26
Satish Gadhave Avatar answered Sep 30 '22 02:09

Satish Gadhave