{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Insert tag\n", "----\n", "\n", "This script recursively inserts a specified tag at the beginning of each line in both `.txt` and `.tags` files within a given directory and its subdirectories." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "\n", "# Function to insert a specified tag in text files in subdirectories\n", "def insert_tag_in_files(directory, tag_to_insert):\n", " try:\n", " for entry in os.listdir(directory):\n", " entry_path = os.path.join(directory, entry)\n", "\n", " if os.path.isdir(entry_path):\n", " insert_tag_in_files(entry_path, tag_to_insert)\n", "\n", " elif os.path.isfile(entry_path) and (entry.endswith(\".txt\") or entry.endswith(\".tags\")):\n", " with open(entry_path, 'r', encoding='utf-8') as f:\n", " content = f.read()\n", "\n", " # Insert the specified tag\n", " content = tag_to_insert + ', ' + content\n", "\n", " # Write back to the file\n", " with open(entry_path, 'w', encoding='utf-8') as f:\n", " f.write(content)\n", "\n", " except Exception as e:\n", " print(f\"Error processing directory {directory}: {e}\\n\")\n", "\n", "directory_path = r'C:\\Users\\kade\\Desktop\\training_dir_staging'\n", "\n", "# Execute the function with the desired tag\n", "insert_tag_in_files(directory_path, 'furrysticker')" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }