1

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.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

You can use os.makedirs to create the entire path at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.