Python Forum
Recursively place file in a directory/all subdirectories
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursively place file in a directory/all subdirectories
#1
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)
Reply
#2
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!
Reply
#3
hell yeah looking at pathlib.Path.touch() right now... awesome

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Making turtle draw a sine wave recursively rootVIII 2 6,271 Jun-09-2019, 07:31 AM
Last Post: rootVIII

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.