I am writing a PowerShell script to create several directories if they do not exist.
The filesystem looks similar to this
D:\ D:\TopDirec\SubDirec\Project1\Revision1\Reports\ D:\TopDirec\SubDirec\Project2\Revision1\ D:\TopDirec\SubDirec\Project3\Revision1\
I need to write a script that runs daily to create these folders for each directory.
I am able to write the script to create a folder, but creating several folders is problematic.
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.
Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.
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.
Try the -Force
parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container
to check first.
See the New-Item MSDN help article for more details.
$path = "C:\temp\NewFolder" If(!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path }
Test-Path
checks to see if the path exists. When it does not, it will create a new directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With