Question

How do I create directories in Python given a list of files with paths that may or may not exist?

I am downloading some files from s3 that may or may not exist in a certain directory. Based upon these keys that represent a potentially deeply nested directory that may or may not exist.

So based upon the key /a/number/of/nested/dirs/file.txt how can I created /a/number/of/nested/dirs/ if they do not exist and do it in a way that doesn't take forever to check for each file in the list.

I am doing this because if the local parent directories do not already exist get_contents_to_filename breaks.

My Final Solution Using Answer:

for file_with_path in files_with_paths:
    try:
        if not os.path.exists(file_with_path):
            os.makedirs(file_with_path)
        site_object.get_contents_to_filename(file_with_path)
    except:
        pass
Was it helpful?

Solution

Simply use os.makedirs(). This will create all intermediate directories if needed.

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Raises an error exception if the leaf directory already exists or cannot be created. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top