{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "All the IPython Notebooks in this lecture series by Dr. Milan Parmar are available @ **[GitHub](https://github.com/milaan9/05_Python_Files)**\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Directory and Files Management\n", "\n", "In this class, you'll learn about file and directory management in Python, i.e. creating a directory, renaming it, listing all directories, and working with them.\n", "\n", "## Python Directory\n", "\n", "If there are a large number of **[files](https://github.com/milaan9/05_Python_Files/blob/main/001_Python_File_Input_Output.ipynb)** to handle in our Python program, we can arrange our code within different directories to make things more manageable.\n", "\n", "A directory or folder is a collection of files and subdirectories. Python has the **`os`** **[module](https://github.com/milaan9/04_Python_Functions/blob/main/007_Python_Function_Module.ipynb)** that provides us with many useful methods to work with directories (and files as well)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Get Current Directory `getcwd()` - \n", "\n", "We can get the present working directory using the **`getcwd()`** method of the os module.\n", "\n", "This method returns the current working directory in the form of a string. We can also use the **`getcwd()`** method to get it as bytes object." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:18.948260Z", "start_time": "2021-06-18T15:35:18.942401Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Users\\Deepak\\01_Learn_Python4Data\\05_Python_Files\n" ] } ], "source": [ "import os\n", "print(os.getcwd())" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:20.242197Z", "start_time": "2021-06-18T15:35:20.220713Z" } }, "outputs": [ { "data": { "text/plain": [ "b'C:\\\\Users\\\\Deepak\\\\01_Learn_Python4Data\\\\05_Python_Files'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "os.getcwdb()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The extra backslash implies an escape sequence. The **`print()`** function will render this properly." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Changing Directory `chdir()` - \n", "\n", "We can change the current working directory by using the **`chdir()`** method.\n", "\n", "The new path that we want to change into must be supplied as a string to this method. We can use both the forward-slash **`/`** or the backward-slash **`\\`** to separate the path elements.\n", "\n", "It is safer to use an escape sequence when using the backward slash.\n", "\n", "**Syntax:**\n", "\n", "**`os.chdir(\"newdir\")`**\n", "\n", ">**Remember to**: \n", "1. First copy the path for current working directory \n", "2. Windows user and MacOS users, first create an empty folder with name \"**xyz**\" on your desktop." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:41.789882Z", "start_time": "2021-06-18T15:35:41.773772Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Directory changed\n", "C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\n" ] } ], "source": [ "import os\n", "\n", "# Changing a directory to \"C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\"\n", "os.chdir(r\"C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\") \n", " \n", "print(\"Directory changed\") \n", "\n", "print(os.getcwd())" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:44.970521Z", "start_time": "2021-06-18T15:35:44.950018Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\n" ] } ], "source": [ "import os\n", "print(os.getcwd())" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:45.765437Z", "start_time": "2021-06-18T15:35:45.749818Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Directory changed\n" ] } ], "source": [ "import os\n", "\n", "# Changing a directory back to original directory \"C:\\Users\\Deepak\\01_Learn_Python4Data\\05_Python_Files\"\n", "os.chdir(r\"C:\\Users\\Deepak\\01_Learn_Python4Data\\05_Python_Files\") \n", " \n", "print(\"Directory changed\") " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:47.044728Z", "start_time": "2021-06-18T15:35:47.037894Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Users\\Deepak\\01_Learn_Python4Data\\05_Python_Files\n" ] } ], "source": [ "import os\n", "print(os.getcwd())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List Directories and Files `listdir()` - \n", "\n", "The **`listdir()`** method displays all files and sub-directories inside a directory.\n", "\n", "This method takes in a path and returns a list of subdirectories and files in that path. If no path is specified, it returns the list of subdirectories and files from the current working directory." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:50.849874Z", "start_time": "2021-06-18T15:35:50.830348Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Users\\Deepak\\01_Learn_Python4Data\\05_Python_Files\n" ] }, { "data": { "text/plain": [ "['.ipynb_checkpoints',\n", " '001_Python_File_Input_Output.ipynb',\n", " '002_Python_File_Directory.ipynb',\n", " '003_Python_File_Exception.ipynb',\n", " '004_Python_Exceptions_Handling.ipynb',\n", " '005_Python_User_defined_Exceptions.ipynb',\n", " 'data.txt',\n", " 'data_1.txt',\n", " 'img',\n", " 'logo.png',\n", " 'logo1.png',\n", " 'test.txt',\n", " 'testfile',\n", " 'test_1.txt',\n", " 'test_2.txt']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(os.getcwd())\n", "\n", "os.listdir()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:35:55.791730Z", "start_time": "2021-06-18T15:35:55.775132Z" }, "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "['$Recycle.Bin',\n", " '$WinREAgent',\n", " '$WINRE_BACKUP_PARTITION.MARKER',\n", " 'bootTel.dat',\n", " 'Documents and Settings',\n", " 'DumpStack.log',\n", " 'DumpStack.log.tmp',\n", " 'hiberfil.sys',\n", " 'ImDisk',\n", " 'OneDriveTemp',\n", " 'pagefile.sys',\n", " 'PerfLogs',\n", " 'Program Files',\n", " 'Program Files (x86)',\n", " 'ProgramData',\n", " 'Python99',\n", " 'Recovery',\n", " 'swapfile.sys',\n", " 'System Volume Information',\n", " 'Users',\n", " 'Windows']" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir('C:\\\\')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Making a New Directory `mkdir()` - \n", "\n", "You can use the **`mkdir()`** method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.\n", "\n", "This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.\n", "\n", "**Syntax:**\n", "\n", "**`os.mkdir(\"dir_name\")`**" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:36:04.319983Z", "start_time": "2021-06-18T15:36:04.301919Z" }, "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Directory created\n" ] }, { "data": { "text/plain": [ "['.ipynb_checkpoints',\n", " '001_Python_File_Input_Output.ipynb',\n", " '002_Python_File_Directory.ipynb',\n", " '003_Python_File_Exception.ipynb',\n", " '004_Python_Exceptions_Handling.ipynb',\n", " '005_Python_User_defined_Exceptions.ipynb',\n", " 'data.txt',\n", " 'data_1.txt',\n", " 'img',\n", " 'logo.png',\n", " 'logo1.png',\n", " 'python_study',\n", " 'test.txt',\n", " 'testfile',\n", " 'test_1.txt',\n", " 'test_2.txt']" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "os.mkdir('python_study')\n", "print(\"Directory created\") \n", "\n", "os.listdir()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Renaming a Directory or a File `rename()` - \n", "\n", "The **`rename()`** method can rename a directory or a file.\n", "\n", "**Syntax:**\n", "\n", "**`os.rename(current_file_name, new_file_name)`**" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:36:08.074352Z", "start_time": "2021-06-18T15:36:08.062629Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Directory renamed\n" ] }, { "data": { "text/plain": [ "['.ipynb_checkpoints',\n", " '001_Python_File_Input_Output.ipynb',\n", " '002_Python_File_Directory.ipynb',\n", " '003_Python_File_Exception.ipynb',\n", " '004_Python_Exceptions_Handling.ipynb',\n", " '005_Python_User_defined_Exceptions.ipynb',\n", " 'data.txt',\n", " 'data_1.txt',\n", " 'img',\n", " 'logo.png',\n", " 'logo1.png',\n", " 'python_learning',\n", " 'test.txt',\n", " 'testfile',\n", " 'test_1.txt',\n", " 'test_2.txt']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir()\n", "\n", "os.rename('python_study','python_learning')\n", "print(\"Directory renamed\") \n", "\n", "os.listdir()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:36:20.064003Z", "start_time": "2021-06-18T15:36:20.055216Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "file renamed\n" ] } ], "source": [ "import os\n", "os.rename('data_1.txt','my_data.txt')\n", "print(\"file renamed\") " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Removing a Directory or a File `remove()` and `rmdir()` - \n", "\n", "A file can be removed (deleted) using the **`remove()`** method.\n", "Similarly, the **`rmdir()`** method removes an empty directory. Before removing a directory, all the contents in it should be removed." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:36:32.627869Z", "start_time": "2021-06-18T15:36:32.598577Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Directory deleted\n" ] }, { "data": { "text/plain": [ "['.ipynb_checkpoints',\n", " '001_Python_File_Input_Output.ipynb',\n", " '002_Python_File_Directory.ipynb',\n", " '003_Python_File_Exception.ipynb',\n", " '004_Python_Exceptions_Handling.ipynb',\n", " '005_Python_User_defined_Exceptions.ipynb',\n", " 'data.txt',\n", " 'img',\n", " 'logo.png',\n", " 'logo1.png',\n", " 'my_data.txt',\n", " 'python_learning',\n", " 'test.txt',\n", " 'testfile',\n", " 'test_1.txt',\n", " 'test_2.txt']" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "\n", "# This would remove \"C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\" directory.\n", "os.rmdir(r\"C:\\Users\\Deepak\\OneDrive\\Desktop\\xyz\")\n", "print(\"Directory deleted\") \n", "\n", "os.listdir()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:36:40.443239Z", "start_time": "2021-06-18T15:36:40.432499Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "file deleted\n" ] } ], "source": [ "import os\n", "os.remove('my_data.txt')\n", "print(\"file deleted\") " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ">**Note**: The **`rmdir()`** method can only remove empty directories." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to remove a non-empty directory, we can use the **`rmtree()`** method inside the **`shutil`** module." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "ExecuteTime": { "end_time": "2021-06-18T15:37:00.249730Z", "start_time": "2021-06-18T15:37:00.241919Z" } }, "outputs": [ { "data": { "text/plain": [ "['.ipynb_checkpoints',\n", " '001_Python_File_Input_Output.ipynb',\n", " '002_Python_File_Directory.ipynb',\n", " '003_Python_File_Exception.ipynb',\n", " '004_Python_Exceptions_Handling.ipynb',\n", " '005_Python_User_defined_Exceptions.ipynb',\n", " 'data.txt',\n", " 'img',\n", " 'logo.png',\n", " 'logo1.png',\n", " 'test.txt',\n", " 'testfile',\n", " 'test_1.txt',\n", " 'test_2.txt']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import shutil\n", "\n", "shutil.rmtree('python_learning')\n", "os.listdir()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "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.8.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }