From cf51a4b90b2f20692ddcf9495ead0ea05fc58b2b Mon Sep 17 00:00:00 2001 From: Junior Date: Sat, 19 Apr 2025 10:42:02 -0400 Subject: [PATCH] Add a script showing the use of pathlib and rglob to catalog files in a set of folders which can output in CSV format --- Python/Examples/catalog_videos.py | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100755 Python/Examples/catalog_videos.py diff --git a/Python/Examples/catalog_videos.py b/Python/Examples/catalog_videos.py new file mode 100755 index 0000000..42b20f3 --- /dev/null +++ b/Python/Examples/catalog_videos.py @@ -0,0 +1,57 @@ +#!/usr/bin/python + +import os +import pathlib +import sys + +def usage(): + print("Usage: catalog_videos.py [output_folder]") + print(" is the folder to start locating videos") + print(" [output_folder] is where catalog files will be written") + print(" this is optional an defaults to CWD") + print() + print("This program will recursively locate all files") + print("located beneath a specified folder and output") + print("the results in a comma separated value list (CSV)") + print() + sys.exit() + +# If no arguments provided then show usage and exit +if len(sys.argv) == 1: + usage() + +# If root_folder is not a directory then show usage and exit +if not os.path.isdir(sys.argv[1]): + print(f"Error: Folder \"{sys.argv[1]}\" does not exist.") + usage() + +# If an output folder is provided then make sure it exists +output_dir = "." +if len(sys.argv) == 3: + if os.path.isdir(sys.argv[2]): + output_dir = sys.argv[2] + else: + print(f"Error: Output folder \"{sys.argv[2]}\" does not exist.") + usage() + +root_dir = sys.argv[1] +root_path = pathlib.Path(root_dir) + +# Walk the root_folder +for item in root_path.glob("*"): + file_contents = "Root Folder,File Name\n" + # If item is a subfolder, walk that + if item.is_dir(): + file_count = 0 + for subitem in item.rglob("*"): + if subitem.is_file(): + file_count += 1 + file_contents += f"{item.name},{subitem.name}\n" + # If subfolder has any items then output the results + # This ensures we don't overwrite contents if the folder + # is suddenly empty or the drive has failed + if file_count != 0: + with open(os.path.join(output_dir, item.name + ".csv"), "w") as f: + f.write(file_contents) + +# vim: ts=4 sw=4 et ai mouse-=a: