|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "attachments": {}, |
| 5 | + "cell_type": "markdown", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "# Working with files\n", |
| 9 | + "\n", |
| 10 | + "A lot of the work you'll do in Python will have the following structure:\n", |
| 11 | + "1. Read data from a file\n", |
| 12 | + "2. Perform computations on the data\n", |
| 13 | + "3. Visualize the results and/or save the results to a file\n", |
| 14 | + "\n", |
| 15 | + "So far, we have only learned about computations. So let's learn a bit about how to manage files. Actually, opening or saving files is usually done with the help of modules which you will learn in more detail in Notebook 4 and 6. What we'll discuss here is how to manage file paths.\n", |
| 16 | + "\n", |
| 17 | + "### File paths\n", |
| 18 | + "\n", |
| 19 | + "To learn how to use files we need to learn how file paths in computers work. If you are tech-savvy and know how file paths work you can skip this part.\n", |
| 20 | + "\n", |
| 21 | + "File paths in computers work like a tree. They start at the <b>root</b> directory, which is often the <b><code>C:</code></b> drive (in Windows). This is the name of the hard drive that stores your Operating System. From the <b><code>C:</code></b> drive you can navigate into other directories. This is done using the **``\\``** character, however in other Operating Systems often the <b><code>/</code></b> delimiter is used.\n", |
| 22 | + "\n", |
| 23 | + "If a file is in the folder <b><code>Users</code></b>, which is stored in the <b><code>C:</code></b> directory, the file path would be <b><code>C:\\Users</code></b>. These types of file paths are called <b>absolute paths</b>. This file path is valid for most computers that run Windows, but some other Operating Systems may have different folder setups. This is why it is useful to use <b>relative paths</b>. Relative paths do not start from the root directory. Instead, they start from the directory you are currently in. By default, Jupyter Notebooks are stored in <b><code>C:\\Users\\CurrentUser</code></b> (where <b><code>CurrentUser</code></b> is your Windows username). To move into a directory using a relative path, for example, to the desktop folder, you would just write <b><code>.\\Desktop</code></b>. To move back a directory, using a relative path, you would type <b><code>..</code></b>\n", |
| 24 | + "\n", |
| 25 | + "`os.listdir()` or `os.listdir('./')` list all the entries in your current directory `os.listdir('../')` list all entries if we go back one level. \n", |
| 26 | + "\n", |
| 27 | + ":::{note}\n", |
| 28 | + "We use the `/` as delimiter, since a `\\` won't work on macOS\n", |
| 29 | + ":::" |
| 30 | + ] |
| 31 | + }, |
| 32 | + { |
| 33 | + "cell_type": "code", |
| 34 | + "execution_count": 2, |
| 35 | + "metadata": { |
| 36 | + "nbgrader": { |
| 37 | + "grade": false, |
| 38 | + "locked": true, |
| 39 | + "solution": false |
| 40 | + } |
| 41 | + }, |
| 42 | + "outputs": [ |
| 43 | + { |
| 44 | + "name": "stdout", |
| 45 | + "output_type": "stream", |
| 46 | + "text": [ |
| 47 | + "['01.ipynb']\n", |
| 48 | + "['01.ipynb']\n", |
| 49 | + "['Exercises', 'In_a_Nutshell', 'Theory']\n" |
| 50 | + ] |
| 51 | + } |
| 52 | + ], |
| 53 | + "source": [ |
| 54 | + "import os\n", |
| 55 | + "\n", |
| 56 | + "print(os.listdir())\n", |
| 57 | + "print(os.listdir('./'))\n", |
| 58 | + "\n", |
| 59 | + "print(os.listdir('../'))" |
| 60 | + ] |
| 61 | + }, |
| 62 | + { |
| 63 | + "attachments": {}, |
| 64 | + "cell_type": "markdown", |
| 65 | + "metadata": { |
| 66 | + "nbgrader": { |
| 67 | + "grade": false, |
| 68 | + "locked": true, |
| 69 | + "solution": false |
| 70 | + } |
| 71 | + }, |
| 72 | + "source": [ |
| 73 | + ":::{warning}\n", |
| 74 | + "Keep in mind that, in Python, all file paths must be strings!\n", |
| 75 | + ":::" |
| 76 | + ] |
| 77 | + }, |
| 78 | + { |
| 79 | + "attachments": {}, |
| 80 | + "cell_type": "markdown", |
| 81 | + "metadata": { |
| 82 | + "nbgrader": { |
| 83 | + "grade": false, |
| 84 | + "locked": true, |
| 85 | + "solution": false |
| 86 | + } |
| 87 | + }, |
| 88 | + "source": [ |
| 89 | + "### ``pathlib`` and <code>os</code> modules\n", |
| 90 | + "\n", |
| 91 | + "These modules are very useful in managing and navigating your file paths. The function <b><code>path.expanduser('~')</code></b>, from the <b><code>os</code></b> module, allows you to find your root directory, independent of your Operating System. Try the below cell to see it." |
| 92 | + ] |
| 93 | + }, |
| 94 | + { |
| 95 | + "cell_type": "code", |
| 96 | + "execution_count": 5, |
| 97 | + "metadata": { |
| 98 | + "nbgrader": { |
| 99 | + "grade": false, |
| 100 | + "locked": true, |
| 101 | + "solution": false |
| 102 | + } |
| 103 | + }, |
| 104 | + "outputs": [ |
| 105 | + { |
| 106 | + "name": "stdout", |
| 107 | + "output_type": "stream", |
| 108 | + "text": [ |
| 109 | + "C:\\Users\\mmendozalugo\n" |
| 110 | + ] |
| 111 | + } |
| 112 | + ], |
| 113 | + "source": [ |
| 114 | + "from pathlib import Path\n", |
| 115 | + "import os\n", |
| 116 | + "\n", |
| 117 | + "root_path = os.path.expanduser('~')\n", |
| 118 | + "print(root_path)\n" |
| 119 | + ] |
| 120 | + }, |
| 121 | + { |
| 122 | + "attachments": {}, |
| 123 | + "cell_type": "markdown", |
| 124 | + "metadata": { |
| 125 | + "nbgrader": { |
| 126 | + "grade": false, |
| 127 | + "locked": true, |
| 128 | + "solution": false |
| 129 | + } |
| 130 | + }, |
| 131 | + "source": [ |
| 132 | + "The path shown above is thus the absolute path to your current directory.\n", |
| 133 | + "\n", |
| 134 | + "This can come in handy when you write a code that needs to create directories in the user's computer to save data files and/or plots. As an example, the code below checks if a directory exists and, if it doesn't, it creates one.\n", |
| 135 | + "\n", |
| 136 | + "The `os.path.join` is used to concatenate two strings to form a path string with the appropriate delimiter.\n", |
| 137 | + "\n", |
| 138 | + "The code will check if a directory named `plots` exists in your current directory if not, it will create one." |
| 139 | + ] |
| 140 | + }, |
| 141 | + { |
| 142 | + "cell_type": "code", |
| 143 | + "execution_count": null, |
| 144 | + "metadata": {}, |
| 145 | + "outputs": [], |
| 146 | + "source": [ |
| 147 | + "print('Contents of current directory (before):')\n", |
| 148 | + "print(os.listdir(root_path))\n", |
| 149 | + "\n", |
| 150 | + "imdir = os.path.join(root_path,'plots') \n", |
| 151 | + "print(f'\\nimdir = {imdir}')\n", |
| 152 | + "\n", |
| 153 | + "Path(imdir).mkdir(parents=True, exist_ok=True)\n", |
| 154 | + "\n", |
| 155 | + "print('\\nContents of current directory (after creating the new directory):')\n", |
| 156 | + "print(os.listdir(root_path))\n" |
| 157 | + ] |
| 158 | + }, |
| 159 | + { |
| 160 | + "cell_type": "code", |
| 161 | + "execution_count": 17, |
| 162 | + "metadata": { |
| 163 | + "tags": [ |
| 164 | + "remove-input" |
| 165 | + ] |
| 166 | + }, |
| 167 | + "outputs": [ |
| 168 | + { |
| 169 | + "name": "stdout", |
| 170 | + "output_type": "stream", |
| 171 | + "text": [ |
| 172 | + "Contents of current directory (before):\n", |
| 173 | + "['Exercises', 'In_a_Nutshell', 'Theory']\n", |
| 174 | + "imdir = C:\\Users\\mmendozalugo\\plots\n", |
| 175 | + "\n", |
| 176 | + "Contents of current directory (after creating the new directory):\n", |
| 177 | + "['Exercises', 'In_a_Nutshell', 'plots', 'Theory']\n" |
| 178 | + ] |
| 179 | + } |
| 180 | + ], |
| 181 | + "source": [ |
| 182 | + "root_path = r'C:\\Users\\mmendozalugo\\OneDrive\\PhD\\Work\\Python_MOOC\\PM\\learn-python\\book\\03'\n", |
| 183 | + "\n", |
| 184 | + "print('Contents of current directory (before):')\n", |
| 185 | + "print(os.listdir(root_path))\n", |
| 186 | + "\n", |
| 187 | + "imdir = os.path.join(root_path,'plots') \n", |
| 188 | + "print('imdir = ',r'C:\\Users\\mmendozalugo\\plots')\n", |
| 189 | + "\n", |
| 190 | + "Path(imdir).mkdir(parents=True, exist_ok=True)\n", |
| 191 | + "\n", |
| 192 | + "print('\\nContents of current directory (after creating the new directory):')\n", |
| 193 | + "print(os.listdir(root_path))\n" |
| 194 | + ] |
| 195 | + }, |
| 196 | + { |
| 197 | + "attachments": {}, |
| 198 | + "cell_type": "markdown", |
| 199 | + "metadata": {}, |
| 200 | + "source": [ |
| 201 | + "To delete the folder that was just created we run the code bellow." |
| 202 | + ] |
| 203 | + }, |
| 204 | + { |
| 205 | + "cell_type": "code", |
| 206 | + "execution_count": null, |
| 207 | + "metadata": {}, |
| 208 | + "outputs": [], |
| 209 | + "source": [ |
| 210 | + "try:\n", |
| 211 | + " os.rmdir(imdir)\n", |
| 212 | + " print(f'Directory {imdir} has been deleted.')\n", |
| 213 | + "except:\n", |
| 214 | + " print('You already deleted the folder. :)')" |
| 215 | + ] |
| 216 | + }, |
| 217 | + { |
| 218 | + "cell_type": "code", |
| 219 | + "execution_count": 18, |
| 220 | + "metadata": { |
| 221 | + "tags": [ |
| 222 | + "remove-input" |
| 223 | + ] |
| 224 | + }, |
| 225 | + "outputs": [ |
| 226 | + { |
| 227 | + "name": "stdout", |
| 228 | + "output_type": "stream", |
| 229 | + "text": [ |
| 230 | + "Directory C:\\Users\\mmendozalugo\\plots has been deleted.\n" |
| 231 | + ] |
| 232 | + } |
| 233 | + ], |
| 234 | + "source": [ |
| 235 | + "print('Directory', r'C:\\Users\\mmendozalugo\\plots','has been deleted.')\n" |
| 236 | + ] |
| 237 | + }, |
| 238 | + { |
| 239 | + "attachments": {}, |
| 240 | + "cell_type": "markdown", |
| 241 | + "metadata": { |
| 242 | + "nbgrader": { |
| 243 | + "grade": false, |
| 244 | + "locked": true, |
| 245 | + "solution": false |
| 246 | + } |
| 247 | + }, |
| 248 | + "source": [ |
| 249 | + "Now you are, hopefully, a bit more used to working with file paths. For the next test, we are going to try to open a file. We can use some built-in Python functions to open a <b><i>*.txt</i></b> file and print its contents." |
| 250 | + ] |
| 251 | + }, |
| 252 | + { |
| 253 | + "cell_type": "markdown", |
| 254 | + "metadata": {}, |
| 255 | + "source": [ |
| 256 | + "## Additional study material\n", |
| 257 | + "\n", |
| 258 | + "* Official Python Documentation - https://docs.python.org/3/tutorial/inputoutput.html\n", |
| 259 | + "* https://realpython.com/python-f-strings/\n", |
| 260 | + "* Official Python Documentation - https://docs.python.org/3/reference/expressions.html\n", |
| 261 | + "* https://realpython.com/python-lambda/\n", |
| 262 | + "* Official Python Documentation - https://docs.python.org/3/library/filesys.html\n", |
| 263 | + "* https://realpython.com/working-with-files-in-python/\n" |
| 264 | + ] |
| 265 | + }, |
| 266 | + { |
| 267 | + "cell_type": "code", |
| 268 | + "execution_count": null, |
| 269 | + "metadata": {}, |
| 270 | + "outputs": [], |
| 271 | + "source": [ |
| 272 | + "After this Notebook you should be able to:\n", |
| 273 | + "\n", |
| 274 | + "- print a variable, formatting it in an appropriate manner\n", |
| 275 | + "- know the existence of escape characters\n", |
| 276 | + "- know how to use lambda functions\n", |
| 277 | + "- understand how file paths work\n", |
| 278 | + "- create and delete new directories \n" |
| 279 | + ] |
| 280 | + } |
| 281 | + ], |
| 282 | + "metadata": { |
| 283 | + "kernelspec": { |
| 284 | + "display_name": "base", |
| 285 | + "language": "python", |
| 286 | + "name": "python3" |
| 287 | + }, |
| 288 | + "language_info": { |
| 289 | + "codemirror_mode": { |
| 290 | + "name": "ipython", |
| 291 | + "version": 3 |
| 292 | + }, |
| 293 | + "file_extension": ".py", |
| 294 | + "mimetype": "text/x-python", |
| 295 | + "name": "python", |
| 296 | + "nbconvert_exporter": "python", |
| 297 | + "pygments_lexer": "ipython3", |
| 298 | + "version": "3.8.13" |
| 299 | + }, |
| 300 | + "latex_envs": { |
| 301 | + "LaTeX_envs_menu_present": true, |
| 302 | + "autoclose": false, |
| 303 | + "autocomplete": true, |
| 304 | + "bibliofile": "biblio.bib", |
| 305 | + "cite_by": "apalike", |
| 306 | + "current_citInitial": 1, |
| 307 | + "eqLabelWithNumbers": true, |
| 308 | + "eqNumInitial": 1, |
| 309 | + "hotkeys": { |
| 310 | + "equation": "Ctrl-E", |
| 311 | + "itemize": "Ctrl-I" |
| 312 | + }, |
| 313 | + "labels_anchors": false, |
| 314 | + "latex_user_defs": false, |
| 315 | + "report_style_numbering": false, |
| 316 | + "user_envs_cfg": false |
| 317 | + } |
| 318 | + }, |
| 319 | + "nbformat": 4, |
| 320 | + "nbformat_minor": 2 |
| 321 | +} |
0 commit comments