{ "cells": [ { "cell_type": "markdown", "id": "68c7448d", "metadata": {}, "source": [ "# Python Basics - 06. File Input / Output\n", "\n", "Reading from and writing to files is an essential part of programming. In Python, the built-in `open()` function paired with the `with` statement makes this extremely safe and straightforward." ] }, { "cell_type": "markdown", "id": "0ce6f7de", "metadata": { "language": "markdown" }, "source": [ "## Download Notebook\n", "\n", "{download}`Download this notebook <06_file_io.ipynb>`\n" ] }, { "cell_type": "markdown", "id": "2999232f", "metadata": {}, "source": [ "## 1. Writing to a File\n", "\n", "To write to a file, use the `open()` function with the mode `\"w\"` (write). **Warning:** `\"w\"` mode will overwrite the file entirely if it already exists! Use `\"a\"` (append) to add text without deleting existing content.\n", "\n", "The `with` block is an excellent practice because it automatically closes the file once the block is exited, avoiding memory or file locks." ] }, { "cell_type": "code", "execution_count": null, "id": "d7e8d996", "metadata": {}, "outputs": [], "source": [ "file_path = \"sample_text.txt\"\n", "\n", "with open(file_path, \"w\") as file_object:\n", " file_object.write(\"Hello, Python File I/O!\\n\")\n", " file_object.write(\"This is the second line.\\n\")\n", " file_object.write(\"Data persistence is wonderful.\")\n", "\n", "print(f\"Successfully wrote to '{file_path}'.\")" ] }, { "cell_type": "markdown", "id": "32258e83", "metadata": {}, "source": [ "## 2. Reading from a File\n", "\n", "To read, you use the mode `\"r\"` (which is the default, so you can omit it). The `read()` method pulls the whole file as a single string." ] }, { "cell_type": "code", "execution_count": null, "id": "953844c0", "metadata": {}, "outputs": [], "source": [ "print(f\"Reading the entire content of '{file_path}':\\n\")\n", "\n", "with open(file_path, \"r\") as file_object:\n", " full_content = file_object.read()\n", " print(full_content)" ] }, { "cell_type": "markdown", "id": "22699415", "metadata": {}, "source": [ "## 3. Reading Line by Line\n", "\n", "For large files, loading everything into memory at once is slow and uses huge amounts of RAM. Instead, you can loop over the file object directly to process one line at a time." ] }, { "cell_type": "code", "execution_count": null, "id": "95e33147", "metadata": {}, "outputs": [], "source": [ "print(\"Processing line by line:\")\n", "with open(file_path, \"r\") as f:\n", " for line_number, line in enumerate(f, 1):\n", " # Use strip() to remove the hidden newline character `\\n` at the end of every line\n", " print(f\"Line {line_number}: {line.strip()}\")\n", "\n", "# Cleanup: Deleting the test file\n", "import os\n", "if os.path.exists(file_path):\n", " os.remove(file_path)\n", " print(f\"\\nCleaned up: '{file_path}' has been deleted.\")" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }