In config of my app I've a path, for example "logs\updater\updater.log"
Starting the app, I want to create the file updater.log, creating all subfolders if they not exists.
So, if tomorrow my user changes the path in config to "logs\mypathisbetter\updater.log", my app continues to work, writing log to the new file.
File.Create
, FileInfo.Create
, Streamwriter.Create
or so: they do that?
Or do I need to check if folders exists, before?
I can't find a clear answer to this question on the net.
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.
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.
A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.
When mkdir fails, it doesn't create nothing. But it creates a file. There's no problems to have a file and a folder with the same name in the same directory. In addition, the script now stops on the directory, that doesn't have a file near itself with the same name.
Solved using a little bit of code:
private static void EnsureDirectoryExists(string filePath)
{
FileInfo fi = new FileInfo(filePath);
if (!fi.Directory.Exists)
{
System.IO.Directory.CreateDirectory(fi.DirectoryName);
}
}
Sorry for this really newbie post... Thank you all! :-)
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