Reputation: 13
Given the following strings:
dir/dir2/dir3/dir3/file.txt
dir/dir2/dir3/file.txt
example/directory/path/file.txt
I am looking to create the correct directories and blank files within those directories.
I imported the os
module and I saw that there is a mkdir
function, but I am not sure what to do to create the whole path and blank files. Any help would be appreciated. Thank you.
Upvotes: 1
Views: 21324
Reputation: 18830
Here is the answer on all your questions (directory creation and blank file creation)
import os
fileList = ["dir/dir2/dir3/dir3/file.txt",
"dir/dir2/dir3/file.txt",
"example/directory/path/file.txt"]
for file in fileList:
dir = os.path.dirname(file)
# create directory if it does not exist
if not os.path.exists(dir):
os.makedirs(dir)
# Create blank file if it does not exist
with open(file, "w"):
pass
Upvotes: 4
Reputation: 30481
First of all, given that try to create directory under a directory that doesn't exist, os.mkdir
will raise an error. As such, you need to walk through the paths and check whether each of the subdirectories has or has not been created (and use mkdir
as required). Alternative, you can use os.makedirs
to handle this iteration for you.
A full path can be split into directory name and filename with os.path.split
.
Example:
import os
(dirname, filename) = os.path.split('dir/dir2/dir3/dir3/file.txt')
os.makedirs(dirname)
Given we have a set of dirs we want to create, simply use a for loop to iterate through them. Schematically:
dirlist = ['dir1...', 'dir2...', 'dir3...']
for dir in dirlist:
os.makedirs( ... )
Upvotes: 1