{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Jupyter notebooks\n",
    "\n",
    "This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Files\n",
    "In Python, it is easy to interact with files on your system by opening them and closing them. The general code structure is as follows:\n",
    "\n",
    "```\n",
    "name_handle = open(file_path, mode)\n",
    "\n",
    "# do some work\n",
    "\n",
    "name_handle.close()\n",
    "```\n",
    "The first line is responsible for opening a file. In it, the variable `file_path` is a string containing the address on your machine of the file you need. For example, `file_path = “C:/HOME/Desktop/my_file.txt` on WindowsOS or `file_path = /usr/Desktop/my_file.txt` on Linux/MacOS. \n",
    "\n",
    "As for `mode`, it is also a string input to the `open` function used to indicate the mode in which you want to open the file:\n",
    "\n",
    "- `mode = \"r\"`: opens the file in read-only mode.\n",
    "- `mode = \"w\"`: opens the file in write mode.\n",
    "- `mode = \"a\"`: opens the file in append mode.\n",
    "\n",
    "There are other modes we will not work with."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `open()` function returns an object of type `_io.TextIOWrapper` and stores it in a variable called `name_handle`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Read-only mode\n",
    "#### In one shot\n",
    "To read the file contents in one shot, use the `.read()` method which returns a string containing the text contents of the file. \n",
    "\n",
    "Example:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-09-27T13:39:47.317233Z",
     "start_time": "2026-09-27T13:39:47.293342Z"
    }
   },
   "source": [
    "def read_file(file_path):\n",
    "    assert type(file_path) == str, \"Bad input!\"\n",
    "    \n",
    "    name_handle = open(file_path, \"r\")\n",
    "    s = name_handle.read()\n",
    "    name_handle.close()\n",
    "    \n",
    "    return s"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2026-09-27T13:39:47.382063Z",
     "start_time": "2026-09-27T13:39:47.320466Z"
    }
   },
   "source": [
    "address = \"my_file.txt\" # change this to your own file path\n",
    "file_contents = read_file(address)\n",
    "print(file_contents)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Hello from my_file.txt!\n",
      "This is the second line.\n",
      "And this is the last line.\n",
      "\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Reading the file line by line\n",
    "You may think of `name_handle` as a sequence, similar to a `list`, `str`, or `tuple`. Therefore, it is an **iterable** and one can use a for-loop to iterate over its contents. Specifically, we can iterate over the file contents line by line.\n",
    "\n",
    "Example:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def display_file(file_path, with_line_number=True):\n",
    "    assert type(file_path) == str, \"Bad Input!\"\n",
    "    \n",
    "    name_handle = open(file_path, \"r\")\n",
    "    \n",
    "    line_number = 1\n",
    "    for line in name_handle:\n",
    "        if with_line_number:\n",
    "            print(\"Line \", line_number, \": \", line, sep=\"\", end=\"\")\n",
    "        else:\n",
    "            print(line, end=\"\")\n",
    "        line_number += 1\n",
    "        \n",
    "    name_handle.close()"
   ],
   "outputs": [],
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "display_file(address)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Line 1: Hello from my_file.txt!\n",
      "Line 2: This is the second line.\n",
      "Line 3: And this is the last line.\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Write Mode\n",
    "Using Python, it is possible to create an empty file using write mode and add contents to it.\n",
    "Example:"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name_handle = open(\"new_file.txt\", \"w\")\n",
    "\n",
    "name_handle.write(\"this is line 1\\n\")\n",
    "name_handle.write(\"this is \")\n",
    "name_handle.write(\"line 2\\n\")\n",
    "name_handle.write(\"last line in file\")\n",
    "\n",
    "name_handle.close()"
   ],
   "outputs": [],
   "execution_count": 5
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above code, the file `new_file.txt` was created in the same folder containing this notebook (because a full path was not specified). The `.write()` method was repeatedly used to write content; notice that the input to this method is a string. The contents of the file are:\n",
    "```\n",
    "this is line 1\n",
    "this is line 2\n",
    "last line in file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Append mode\n",
    "If there's an existing file to which we want to add content, we use the append mode instead of write mode to avoid overwriting its contents. Example:\n"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "name_handle = open(\"new_file.txt\", \"a\") # opens the file previously created\n",
    "\n",
    "name_handle.write(\"this line was added\\n\")\n",
    "name_handle.write(\"this line is new as well\")\n",
    "\n",
    "name_handle.close()"
   ],
   "outputs": [],
   "execution_count": 6
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, the contents of the file `new_file.txt` are:\n",
    "```\n",
    "this is line 1\n",
    "this is line 2\n",
    "last line in filethis line was added\n",
    "this line is new as well\n",
    "\n",
    "```\n",
    "Notice how the string `\"this line was added\"` is appended directly next to the old last line from before `\"last line in file\"`."
   ]
  }
 ],
 "metadata": {
  "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.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
