Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically create directories from long paths

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?

like image 653
Brian David Berman Avatar asked Oct 27 '10 19:10

Brian David Berman


People also ask

How do I automatically create a directory in Python?

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.

How do I create a directory path?

To write a path that moves into a folder we specify the folder name, followed by a forward slash, then the file name.

Does Python open create folders?

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.

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

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 .


1 Answers

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>.

like image 77
TeaDrivenDev Avatar answered Sep 20 '22 18:09

TeaDrivenDev