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.
(new FileInfo(filePath)).Directory.Create()
before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
You can use following code
DirectoryInfo di = Directory.CreateDirectory(path);
As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:
Directory.CreateDirectory(Path.GetDirectoryName(filePath))
An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:
public static class FileInfoExtension
{
//second parameter is need to avoid collision with native MoveTo
public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) {
if (autoCreateDirectory)
{
var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));
if (!destinationDirectory.Exists)
destinationDirectory.Create();
}
file.MoveTo(destination);
}
}
Then use brand new MoveTo extension:
using <namespace of FileInfoExtension>;
...
new FileInfo("some path")
.MoveTo("target path",true);
Check Methods extension documentation.
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