I have a collection of files with fully qualified paths (root/test/thing1/thing2/file.txt). I want to foreach
over this collection and drop the file into the location defined in the path, however, if certain directories don't exist, I want them to great created automatically. My program has a default "drop location", such as z:/
. The "drop location" starts off empty, so in my example above, the first item should automatically create the directories needed to create z:/root/test/thing1/thing2/file.txt
. How can I do this?
Using os.os. makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os. makedirs() method will create them all.
To write a path that moves into a folder we specify the folder name, followed by a forward slash, then the file name.
Python's OS module includes functions for creating and removing directories (folders), retrieving their contents, altering and identifying the current directory, and more. To interface with the underlying operating system, you must first import the os module.
Method 2: Using isdir() and makedirs() In this method, we will use isdir() method takes path of demo_folder2 as an argument and returns true if the directory exists and return false if the directory doesn't exist and makedirs() method is used to create demo_folder2 directory recursively .
foreach (var relativePath in files.Keys)
{
var fullPath = Path.Combine(defaultLocation, relativePath);
var directory = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(directory);
saveFile(fullPath, files[relativePath]);
}
where files is IDictionary<string, object>
.
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