user2521067
user2521067

Reputation: 145

Looping through a list of directories to make subdirectories

I have a directory full of subdirectories.

What I would like to do is write a Python script that loops through each of those sub-directories and for each one it creates an additional subdirectory and populates it with three files.

For example:

directories = ['apple', 'orange', 'banana']

for fruit in directories:

# 1) create subdirectory called "files"
# 2) Populate "files" with file1, file2, file3

I am familiar with creating directories and files on Terminal's command line (Mac) but I don't know how to call those commands from Python.

I would greatly appreciate advice on what those commands look like and how to use them.

Upvotes: 0

Views: 1100

Answers (3)

Alois Mahdal
Alois Mahdal

Reputation: 11243

Python os module has all you need for creating the directories, particularly os.mkdir().

You don't say what you want in that files. If you want a copy of another ("template") file, use shutil.copy() If you want to create a new file and wrrite from that from your script, a built-in open() will suffice.

Here's an example (note that it assumes that the "fruit" directories already exist in current directory and that subdirectory "files" does not exist yet):

import os
import shutil

directories = ['apple', 'orange', 'banana']

for fruit in directories:

    os.mkdir("%s/files" % fruit)

    with open("%s/files/like" % fruit, "w") as fp:
        fp.write("I like %ss" % fruit)
    fp.close()

    with open("%s/files/hate" % fruit, "w") as fp:
        fp.write("I hate %ss" % fruit)
    fp.close()

    with open("%s/files/dont_care_about" % fruit, "w") as fp:
        fp.write("I don't care about %ss" % fruit)
    fp.close()

Upvotes: 0

Anze
Anze

Reputation: 706

use python import os and os.system('command_to_run_in_shell') and you are ready to go!!

Upvotes: 0

bogatron
bogatron

Reputation: 19169

You can achieve what you want by using the builtin functions os.path.walk (to walk through the directory tree) and os.mkdir (to actually create the directories).

Upvotes: 1

Related Questions