{ "cells": [ { "cell_type": "markdown", "id": "878e2a35", "metadata": {}, "source": [ "# `os` Module\n", "\n", "The `os` module, short for Operating System, offers a portable way of interacting with various operating system-dependent functionalities. [Offical Documentation for the OS module](https://docs.python.org/3/library/os.html?highlight=os#module-os)\n", "\n", "## Importing the os Module\n", "\n", "Before we dive into the various capabilities of the os module, we need to import it into our Python script. This is done using a straightforward import statement:" ] }, { "cell_type": "code", "execution_count": 14, "id": "c8af7ed3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['learn_python', 'bradpenney.ca_hugo', 'learn_enterprise_linux', 'second_brain', 'rust_learning', 'pandas_course', 'Ex_Files_Python_Working_with_Files', 'bingo.py', 'test.py', 'prog_1700', 'Untitled.ipynb', '.ipynb_checkpoints', 'Day_19_Challenge.ipynb', 'Day_19_Challenge.py', 'testing_word_cloud.ipynb', 'python_snippets']\n" ] } ], "source": [ "import os\n", "print(os.listdir('.'))" ] }, { "cell_type": "markdown", "id": "ac2c9a5a-7851-409d-8077-53ed3ff02ae8", "metadata": {}, "source": [ "With this import statement, we gain access to a multitude of methods and functionalities that allow us to interact with the operating system in a platform-independent manner.\n", "\n", "## Navigating Through Directories and Listing Contents\n", "\n", "One of the fundamental tasks when working with files and directories is navigating through the filesystem. The os module provides essential functions for achieving this.\n", "\n", "### Getting the Current Working Directory\n", "\n", "To determine the current working directory, which is the directory where your Python script is running, you can use the `os.getcwd()` method:" ] }, { "cell_type": "code", "execution_count": 15, "id": "d6fa00ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The current working directory is: /home/brad/Documents\n" ] } ], "source": [ "import os\n", "print(f\"The current working directory is: {os.getcwd()}\")" ] }, { "cell_type": "markdown", "id": "54028803", "metadata": {}, "source": [ "This code will output the path to your current working directory.\n", "\n", "### Changing the Current Working Directory\n", "\n", "If you need to switch to a different directory, you can use the `os.chdir('')` method, passing the target path as a string:" ] }, { "cell_type": "code", "execution_count": 16, "id": "221b1fe3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The current working directory is: /home/brad/Documents\n", "The current working directory is: /home/brad\n" ] } ], "source": [ "import os\n", "print(f\"The current working directory is: {os.getcwd()}\")\n", "os.chdir('../') # no output\n", "print(f\"The current working directory is: {os.getcwd()}\")" ] }, { "cell_type": "markdown", "id": "e2919d39-57c1-4064-b9b8-49cb470b212d", "metadata": {}, "source": [ "This example demonstrates how to navigate up one level in the directory hierarchy.\n", "\n", "### Listing Directory Contents\n", "\n", "The `os.listdir('')` method allows you to list the contents of a directory. For instance:" ] }, { "cell_type": "code", "execution_count": 17, "id": "939df0e7-3f38-4df0-a2d1-e90b22f101b9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['.mozilla', '.bash_logout', '.bash_profile', '.bashrc', '.local', '.cache', '.config', 'Desktop', 'Downloads', 'Templates', 'Public', 'Documents', 'Music', 'Pictures', 'Videos', '.ssh', '.ipython', '.jupyter', '.vim', '.pki', 'mu_code', '.zenmap', '.wget-hsts', '.joplin', '.cargo', '.profile', '.rustup', 'book', 'timer.py', '.gnupg', 'anaconda3', '.conda', '.anaconda', '.continuum', '.condarc', 'brad_penney_day_005.py', 'testFile.txt', 'Untitled.ipynb', '.ipynb_checkpoints', 'Demo.ipynb', 'Untitled1.ipynb', '.xsel.log', '.idlerc', 'helloWorld.py', '.vscode-insiders', '.dotnet', 'os_walk_function.py', '.python_history', '.gitconfig', '.viminfo', '.bash_history', '.gtkrc-2.0', '.gtkrc-2.0-kde4', '.virtual_documents']\n" ] } ], "source": [ "import os\n", "contents = os.listdir('.')\n", "print(contents)" ] }, { "cell_type": "markdown", "id": "09f4af97-f151-43ae-b554-bf1b590c729a", "metadata": {}, "source": [ "This code snippet will print a list of strings, representing the contents of the current directory. Keep in mind that `listdir()` does not differentiate between directories and files; it simply returns their names as strings.\n", "\n", "## Working with Directories\n", "### Creating Directories\n", "\n", "The os module empowers you to create directories for organizing files. Two essential functions for this purpose are `os.mkdir('')` and `os.makedirs('')`. The key distinction between them is that `mkdir` can only create a directory if its parent directory already exists, whereas `makedirs` will create the entire parent structure as needed:" ] }, { "cell_type": "code", "execution_count": 18, "id": "bb83d984-c2d2-4d1e-91f9-bb1f39971c87", "metadata": {}, "outputs": [], "source": [ "import os\n", "os.mkdir('./myNewDirectory/') # This will work if the parent directory exists\n", "os.makedirs('./newParentDirectory/myNewDirectory') # This will succeed, creating parent directories as required" ] }, { "cell_type": "markdown", "id": "0e4301ac", "metadata": {}, "source": [ "Both `os.mkdir()` and `os.makdirs` will fail if the directory already exists (a very common scenario when running a program that generates logs).\n", "\n", "```{note}\n", "Use `os.makedirs()` with caution. It is notorious for creating difficult-to-track logical errors. If the directory structure does not exist, it will be created, even if there is an error in the path. So it would be very easy to create `~/newParentDirectry/myNewDirectory` (note the missing \"o\" in \"Directory\").\n", "```\n", "\n", "### Removing Directories\n", "\n", "Getting rid of **empty** directories is also possible. The `os.rmdir()` and `os.removedirs()` functions work in the same way as making directories above - the `os.rmdir` will only remove one directory, wherease the `os.removedirs()` will remove all the parent structure as well. For example:" ] }, { "cell_type": "code", "execution_count": 19, "id": "57b9a051", "metadata": {}, "outputs": [], "source": [ "os.rmdir('./myNewDirectory') # will only remove target directory\n", " # assuming current working directory is /home/prog1700/Desktop/myNewDirectory'\n", "os.removedirs('./newParentDirectory/myNewDirectory') # will remove all empty directories in the path\n" ] }, { "cell_type": "markdown", "id": "1ae791bc", "metadata": {}, "source": [ "```{note}\n", " Both `os.rmdir()` and `os.removedirs()` only work with **empty** directories. As soon as a directory contains either a file or another directory, the command will fail (or, in the case of `os.removedirs()` stop recursively walking up the file tree). Therefore, it is possible to use either relative or absolute paths with these functions, as long as the target directories are empty.\n", "```" ] }, { "cell_type": "markdown", "id": "2b1df36d", "metadata": {}, "source": [ "## Resources\n", "\n", "[![Corey Schafer - Python Tutorial: OS Module - Use Underlying Operating System Functionality](https://img.youtube.com/vi/tJxcKyFMTGo/maxresdefault.jpg)](https://youtu.be/tJxcKyFMTGo)" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "formats": "ipynb,md:myst", "main_language": "python", "notebook_metadata_filter": "-all" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }