File size: 2,216 Bytes
00b2f69 d87b607 00b2f69 d87b607 00b2f69 d87b607 00b2f69 d87b607 00b2f69 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
{
"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": 1,
"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, 'dharrel')\n",
"insert_tag_in_files(directory_path, 'jex')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|