{"id":96,"date":"2025-10-25T06:55:22","date_gmt":"2025-10-25T06:55:22","guid":{"rendered":"https:\/\/codetypingpro.com\/?p=96"},"modified":"2025-12-17T07:49:31","modified_gmt":"2025-12-17T07:49:31","slug":"lesson-25-file-directory-automation-in-python","status":"publish","type":"post","link":"https:\/\/codetypingpro.com\/?p=96","title":{"rendered":"Lesson 25: File &amp; Directory Automation in Python"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">\ud83c\udfaf <strong>Lesson Objective<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To learn how to <strong>automate repetitive file and folder tasks<\/strong> \u2014 such as creating, renaming, moving, and deleting files \u2014 using Python\u2019s built-in modules.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde9 <strong>1. What Is File &amp; Directory Automation?<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>File and directory automation<\/strong> means using Python scripts to automatically perform operations like:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Organizing files (e.g., move images to \u201cPictures\u201d)<\/li>\n\n\n\n<li>Creating backups<\/li>\n\n\n\n<li>Renaming multiple files at once<\/li>\n\n\n\n<li>Deleting unwanted or duplicate files<\/li>\n\n\n\n<li>Generating folders automatically<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This helps save time and reduce manual effort.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udde0 <strong>2. Modules Used<\/strong><\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Module<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td><code>os<\/code><\/td><td>Interact with the operating system (create\/delete directories, rename files, etc.)<\/td><\/tr><tr><td><code>shutil<\/code><\/td><td>Copy, move, or delete entire files or directories<\/td><\/tr><tr><td><code>glob<\/code><\/td><td>Find files using wildcards (e.g., <code>*.txt<\/code>)<\/td><\/tr><tr><td><code>pathlib<\/code><\/td><td>Modern, object-oriented way to handle file paths<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\u2699\ufe0f <strong>3. Accessing Current Working Directory<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\n# Get the current working directory\ncurrent_dir = os.getcwd()\nprint(\"Current Directory:\", current_dir)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Current Directory: C:\\Users\\Sameer\\Documents\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udcc1 <strong>4. Creating and Removing Directories<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\n# Create a new folder\nos.mkdir(\"MyFolder\")\n\n# Create nested folders\nos.makedirs(\"Projects\/Python\/Automation\")\n\n# Remove a folder (only if empty)\nos.rmdir(\"MyFolder\")\n\n# Remove nested folders\nos.removedirs(\"Projects\/Python\/Automation\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Note:<\/strong> To delete folders that contain files, use <code>shutil.rmtree()<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udcc4 <strong>5. Listing Files and Folders<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\nitems = os.listdir(\".\")  # \".\" means current directory\nprint(\"Files and folders:\", items)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Files and folders: &#91;'main.py', 'data.txt', 'images', 'notes.docx']\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\udeb6 <strong>6. Renaming Files and Folders<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\n# Rename a file\nos.rename(\"old_name.txt\", \"new_name.txt\")\n\n# Rename a folder\nos.rename(\"OldFolder\", \"NewFolder\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udce6 <strong>7. Moving and Copying Files<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Using the <code>shutil<\/code> module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import shutil\n\n# Copy a file\nshutil.copy(\"data.txt\", \"backup\/data_backup.txt\")\n\n# Move a file\nshutil.move(\"notes.txt\", \"Documents\/notes.txt\")\n\n# Delete a file\nos.remove(\"temp.txt\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd0d <strong>8. Searching Files with glob<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import glob\n\n# Find all text files\ntext_files = glob.glob(\"*.txt\")\nprint(text_files)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;'data.txt', 'notes.txt', 'summary.txt']\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also search recursively:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>files = glob.glob(\"**\/*.py\", recursive=True)\nprint(files)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf0 <strong>9. Using <code>pathlib<\/code> for Modern Path Handling<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>from pathlib import Path\n\n# Create a Path object\npath = Path(\"example.txt\")\n\n# Check existence\nif path.exists():\n    print(\"File exists!\")\n\n# Get file details\nprint(\"File name:\", path.name)\nprint(\"Extension:\", path.suffix)\nprint(\"Parent directory:\", path.parent)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udd01 <strong>10. Example 1 \u2014 Auto File Organizer<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Automatically move files into folders based on their types.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nimport shutil\n\nsource = \"Downloads\"\ndest = \"Organized\"\n\n# Create destination folder\nos.makedirs(dest, exist_ok=True)\n\nfor file in os.listdir(source):\n    filepath = os.path.join(source, file)\n\n    if os.path.isfile(filepath):\n        if file.endswith(('.jpg', '.png')):\n            folder = \"Images\"\n        elif file.endswith(('.pdf', '.docx')):\n            folder = \"Documents\"\n        elif file.endswith(('.mp3', '.wav')):\n            folder = \"Audio\"\n        else:\n            folder = \"Others\"\n\n        dest_path = os.path.join(dest, folder)\n        os.makedirs(dest_path, exist_ok=True)\n        shutil.move(filepath, dest_path)\n        print(f\"Moved {file} \u2192 {folder}\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Result:<\/strong><br>Your \u201cDownloads\u201d folder gets automatically sorted into <strong>Images<\/strong>, <strong>Documents<\/strong>, <strong>Audio<\/strong>, and <strong>Others<\/strong> folders.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddf9 <strong>11. Example 2 \u2014 Auto File Renamer<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Rename all <code>.txt<\/code> files to have a numbered sequence.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\n\nfolder = \"Reports\"\nfiles = os.listdir(folder)\n\ncount = 1\nfor file in files:\n    if file.endswith(\".txt\"):\n        old = os.path.join(folder, file)\n        new = os.path.join(folder, f\"report_{count}.txt\")\n        os.rename(old, new)\n        count += 1\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Result:<\/strong><br>Files like <code>data1.txt<\/code>, <code>summary.txt<\/code> \u2192 become \u2192 <code>report_1.txt<\/code>, <code>report_2.txt<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\uddd1\ufe0f <strong>12. Example 3 \u2014 Delete Old Files Automatically<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Delete files older than 7 days.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os, time\n\nfolder = \"Logs\"\nnow = time.time()\n\nfor file in os.listdir(folder):\n    filepath = os.path.join(folder, file)\n    if os.path.isfile(filepath):\n        # Check age in seconds\n        age = now - os.path.getmtime(filepath)\n        if age &gt; 7 * 24 * 60 * 60:\n            os.remove(filepath)\n            print(f\"Deleted old file: {file}\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83e\uddee <strong>13. Example 4 \u2014 Backup Files Automatically<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>import shutil\nimport datetime\n\ntoday = datetime.date.today()\nbackup_folder = f\"Backup_{today}\"\n\nshutil.copytree(\"ProjectData\", backup_folder)\nprint(f\"Backup created: {backup_folder}\")\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u2705 <strong>Result:<\/strong><br>Creates a folder like <code>Backup_2025-10-25<\/code> containing a full copy of <code>ProjectData<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">\ud83d\udca1 <strong>14. Example 5 \u2014 Directory Tree Printer<\/strong><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>from pathlib import Path\n\ndef print_tree(path, level=0):\n    for item in path.iterdir():\n        print(\" \" * level * 2 + \"|--\", item.name)\n        if item.is_dir():\n            print_tree(item, level + 1)\n\nprint_tree(Path(\".\"))\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>|-- Documents\n  |-- notes.txt\n  |-- images\n    |-- photo1.jpg\n|-- main.py\n|-- data.csv\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udfaf Lesson Objective To learn how to automate repetitive file and folder tasks \u2014 such as creating, renaming, moving, and deleting files \u2014 using Python\u2019s built-in modules. \ud83e\udde9 1. What Is File &amp; Directory Automation? File and directory automation means using Python scripts to automatically perform operations like: This helps save time and reduce manual [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,1],"tags":[],"class_list":["post-96","post","type-post","status-publish","format-standard","hentry","category-python-easy-course-outline","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/96","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=96"}],"version-history":[{"count":3,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/96\/revisions"}],"predecessor-version":[{"id":99,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=\/wp\/v2\/posts\/96\/revisions\/99"}],"wp:attachment":[{"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=96"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=96"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetypingpro.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=96"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}