Python Forum

Full Version: Recursively place file in a directory/all subdirectories
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Having some fun with recursion.

This one places a file in the specified directory as well as its subdirectories and their subdirectories etc. In other words don't specify the file path to be '/'. hahahaha.... unless you write the code to undo it

#! /usr/bin/python3
from os.path import isdir, basename
from os import listdir, system, getcwd, chdir
import sys
# recursively create a file in all subdirectories of a given
# directory.. all dirs/subdirs should have different names


def get_diff(available, removal):
    difference = []
    s1 = set()
    s2 = set()
    s1.update(available)
    s2.update(removal)
    for i in s1.difference(s2):
        difference.append(i)
    return difference


def create(finished_folders):
    chdir("/home/absolute/path/to/directory")
    current_dir = basename(getcwd())
    available_dirs = listdir(".")
    removal_list = []
    for d in available_dirs:
        if d in finished_folders or not isdir(d):
            removal_list.append(d)
    available_dirs = get_diff(available_dirs, removal_list)
    if current_dir not in finished_folders:
        while len(available_dirs) > 0:
            next_dir = available_dirs.pop()
            if next_dir not in finished_folders and isdir(next_dir):
                chdir(next_dir)
                available_dirs = listdir(".")
                for directory in available_dirs:
                    if directory in finished_folders or not isdir(directory):
                        removal_list.append(directory)
                available_dirs = get_diff(available_dirs, removal_list)
        system("touch test.txt")
        finished_folders += [basename(getcwd())]
        create(finished_folders)
    else:
        print("FINISHED")
        sys.exit()


if __name__ == "__main__":
    folders = []
    create(folders)
Is this code for the obfuscated python contest? If you want to add an empty 'test.txt' file in every subfolder of a hierarchy, you can do it with os.walk(). Why use such a complicated function? Even get_diff() can be shortened
def get_diff(available, removal):
    s = set(removal)
    return [x for x in available if x not in s]
Do you know one can 'touch' without a subprocess? There is a pathlib.Path.touch() method that does just that!
hell yeah looking at pathlib.Path.touch() right now... awesome

Actually I was specifically trying to do it without os.walk()....