|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "id": "602c3bd6", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "#### **3. Opening and Closing Files in Python**\n", |
| 9 | + "\n", |
| 10 | + "To work with files in Python, we use the `open()` function.\n", |
| 11 | + "\n", |
| 12 | + "### 🔤 Syntax:\n", |
| 13 | + "```python\n", |
| 14 | + "file = open('filename.txt', 'mode')\n", |
| 15 | + "# Perform operations on the file\n", |
| 16 | + "file.close()\n" |
| 17 | + ] |
| 18 | + }, |
| 19 | + { |
| 20 | + "cell_type": "markdown", |
| 21 | + "id": "80cd34e1", |
| 22 | + "metadata": {}, |
| 23 | + "source": [ |
| 24 | + "### **✅ Always close the file after opening it to free up system resources!**" |
| 25 | + ] |
| 26 | + }, |
| 27 | + { |
| 28 | + "cell_type": "code", |
| 29 | + "execution_count": 2, |
| 30 | + "id": "f4af7a7c", |
| 31 | + "metadata": {}, |
| 32 | + "outputs": [], |
| 33 | + "source": [ |
| 34 | + "# Open the file 'example.txt' in write mode ('w')\n", |
| 35 | + "# If the file doesn't exist, it will be created.\n", |
| 36 | + "# If it does exist, its contents will be overwritten.\n", |
| 37 | + "file = open('example.txt', 'w')\n", |
| 38 | + "\n", |
| 39 | + "# Write a line of text into the file\n", |
| 40 | + "file.write('Hello, this is a sample file sk beekhani!')\n", |
| 41 | + "\n", |
| 42 | + "# Close the file to ensure data is saved and resources are released\n", |
| 43 | + "file.close()" |
| 44 | + ] |
| 45 | + }, |
| 46 | + { |
| 47 | + "cell_type": "markdown", |
| 48 | + "id": "7a7c8024", |
| 49 | + "metadata": {}, |
| 50 | + "source": [ |
| 51 | + "### **4. Reading from and Writing to Files**\n", |
| 52 | + "\n", |
| 53 | + "We can use different **modes** while working with files:\n", |
| 54 | + "\n", |
| 55 | + "- `'r'` → **Read mode** (default)\n", |
| 56 | + "- `'w'` → **Write mode** (creates a new file or overwrites an existing one)\n", |
| 57 | + "- `'a'` → **Append mode** (adds data without deleting existing content)\n", |
| 58 | + "- `'r+'` → **Read and write mode**\n", |
| 59 | + "\n", |
| 60 | + "---\n", |
| 61 | + "\n", |
| 62 | + "### **✍️ Example: Writing and Reading a File in Python**" |
| 63 | + ] |
| 64 | + }, |
| 65 | + { |
| 66 | + "cell_type": "markdown", |
| 67 | + "id": "6d05dd33", |
| 68 | + "metadata": {}, |
| 69 | + "source": [ |
| 70 | + "#### 📘 Example: Read Mode (`'r'`)\n", |
| 71 | + "\n", |
| 72 | + "**Read Mode** (`'r'`) opens a file for reading. \n", |
| 73 | + "⚠️ The file **must exist**, otherwise a `FileNotFoundError` will be raised.\n" |
| 74 | + ] |
| 75 | + }, |
| 76 | + { |
| 77 | + "cell_type": "code", |
| 78 | + "execution_count": 4, |
| 79 | + "id": "b4c45857", |
| 80 | + "metadata": {}, |
| 81 | + "outputs": [ |
| 82 | + { |
| 83 | + "name": "stdout", |
| 84 | + "output_type": "stream", |
| 85 | + "text": [ |
| 86 | + "File Content: Hello, this is a sample file sk beekhani!\n" |
| 87 | + ] |
| 88 | + } |
| 89 | + ], |
| 90 | + "source": [ |
| 91 | + "# Now, let's open the file in read mode ('r') to read its contents\n", |
| 92 | + "try:\n", |
| 93 | + " with open('example.txt', 'r') as file:\n", |
| 94 | + " content = file.read()\n", |
| 95 | + " print('File Content:', content)\n", |
| 96 | + "except FileNotFoundError:\n", |
| 97 | + " print('Error: The file does not exist!')\n" |
| 98 | + ] |
| 99 | + }, |
| 100 | + { |
| 101 | + "cell_type": "markdown", |
| 102 | + "id": "c13c7e7d", |
| 103 | + "metadata": {}, |
| 104 | + "source": [ |
| 105 | + "#### ✍️ Example: Write Mode (`'w'`)\n", |
| 106 | + "\n", |
| 107 | + "**Write Mode** (`'w'`) opens a file for writing. \n", |
| 108 | + "- If the file exists, it **overwrites** the content. \n", |
| 109 | + "- If it doesn't exist, a **new file is created**." |
| 110 | + ] |
| 111 | + }, |
| 112 | + { |
| 113 | + "cell_type": "code", |
| 114 | + "execution_count": 5, |
| 115 | + "id": "54c36dbc", |
| 116 | + "metadata": {}, |
| 117 | + "outputs": [ |
| 118 | + { |
| 119 | + "name": "stdout", |
| 120 | + "output_type": "stream", |
| 121 | + "text": [ |
| 122 | + "File written successfully.\n" |
| 123 | + ] |
| 124 | + } |
| 125 | + ], |
| 126 | + "source": [ |
| 127 | + "\n", |
| 128 | + "try:\n", |
| 129 | + " with open('example.txt', 'w') as file:\n", |
| 130 | + " file.write(\"This content will overwrite any existing text.\")\n", |
| 131 | + " print(\"File written successfully.\")\n", |
| 132 | + "except IOError:\n", |
| 133 | + " print(\"Error: Unable to write to the file.\")\n" |
| 134 | + ] |
| 135 | + }, |
| 136 | + { |
| 137 | + "cell_type": "markdown", |
| 138 | + "id": "dd41625d", |
| 139 | + "metadata": {}, |
| 140 | + "source": [ |
| 141 | + "#### ➕ Example: Append Mode (`'a'`)\n", |
| 142 | + "\n", |
| 143 | + "**Append Mode** (`'a'`) opens a file for appending. \n", |
| 144 | + "- If the file exists, new content is **added to the end** without deleting existing content. \n", |
| 145 | + "- If the file doesn't exist, it will be **created**." |
| 146 | + ] |
| 147 | + }, |
| 148 | + { |
| 149 | + "cell_type": "code", |
| 150 | + "execution_count": 6, |
| 151 | + "id": "868816b2", |
| 152 | + "metadata": {}, |
| 153 | + "outputs": [ |
| 154 | + { |
| 155 | + "name": "stdout", |
| 156 | + "output_type": "stream", |
| 157 | + "text": [ |
| 158 | + "Content appended successfully.\n" |
| 159 | + ] |
| 160 | + } |
| 161 | + ], |
| 162 | + "source": [ |
| 163 | + "try:\n", |
| 164 | + " with open('example.txt', 'a') as file:\n", |
| 165 | + " file.write(\"\\nThis line is added using append mode.\")\n", |
| 166 | + " print(\"Content appended successfully.\")\n", |
| 167 | + "except IOError:\n", |
| 168 | + " print(\"Error: Unable to append to the file.\")\n" |
| 169 | + ] |
| 170 | + }, |
| 171 | + { |
| 172 | + "cell_type": "code", |
| 173 | + "execution_count": 8, |
| 174 | + "id": "995588eb", |
| 175 | + "metadata": {}, |
| 176 | + "outputs": [ |
| 177 | + { |
| 178 | + "name": "stdout", |
| 179 | + "output_type": "stream", |
| 180 | + "text": [ |
| 181 | + "This content will overwrite any existing text.\n", |
| 182 | + "This line is added using append mode.\n", |
| 183 | + "Overwritten content.\n", |
| 184 | + "New line added.\n" |
| 185 | + ] |
| 186 | + } |
| 187 | + ], |
| 188 | + "source": [ |
| 189 | + "# Read mode\n", |
| 190 | + "with open('example.txt', 'r') as f:\n", |
| 191 | + " print(f.read())\n", |
| 192 | + "\n", |
| 193 | + "# Write mode\n", |
| 194 | + "with open('example.txt', 'w') as f:\n", |
| 195 | + " f.write(\"Overwritten content.\")\n", |
| 196 | + "\n", |
| 197 | + "# Append mode\n", |
| 198 | + "with open('example.txt', 'a') as f:\n", |
| 199 | + " f.write(\"\\nNew line added.\")\n", |
| 200 | + "\n", |
| 201 | + "# Read and Write mode\n", |
| 202 | + "with open('example.txt', 'r+') as f:\n", |
| 203 | + " print(f.read())\n", |
| 204 | + " f.write(\"\\nAdding more content with r+ mode.\")\n" |
| 205 | + ] |
| 206 | + }, |
| 207 | + { |
| 208 | + "cell_type": "markdown", |
| 209 | + "id": "03283591", |
| 210 | + "metadata": {}, |
| 211 | + "source": [ |
| 212 | + "#### 5. Working with JSON Files in Python\n", |
| 213 | + "\n", |
| 214 | + "JSON (JavaScript Object Notation) is a popular format for storing and exchanging data. Python provides a built-in `json` module to handle JSON files easily.\n", |
| 215 | + "\n", |
| 216 | + "### Example: Storing and Loading Data Using JSON Files\n" |
| 217 | + ] |
| 218 | + }, |
| 219 | + { |
| 220 | + "cell_type": "code", |
| 221 | + "execution_count": 11, |
| 222 | + "id": "40ae465e", |
| 223 | + "metadata": {}, |
| 224 | + "outputs": [ |
| 225 | + { |
| 226 | + "name": "stdout", |
| 227 | + "output_type": "stream", |
| 228 | + "text": [ |
| 229 | + "Data has been written to 'data.json'.\n", |
| 230 | + "Data loaded from 'data.json': {'name': 'Suresh', 'age': 25, 'city': 'Lahore'}\n" |
| 231 | + ] |
| 232 | + } |
| 233 | + ], |
| 234 | + "source": [ |
| 235 | + "\n", |
| 236 | + "import json\n", |
| 237 | + "\n", |
| 238 | + "# Sample dictionary\n", |
| 239 | + "data = {'name': 'Suresh', 'age': 25, 'city': 'Lahore'}\n", |
| 240 | + "\n", |
| 241 | + "# Writing data to a JSON file\n", |
| 242 | + "with open('data.json', 'w') as file:\n", |
| 243 | + " json.dump(data, file) # Convert dictionary to JSON and write to file\n", |
| 244 | + "\n", |
| 245 | + "print(\"Data has been written to 'data.json'.\")\n", |
| 246 | + "\n", |
| 247 | + "# Reading data from a JSON file\n", |
| 248 | + "with open('data.json', 'r') as file:\n", |
| 249 | + " loaded_data = json.load(file) # Read JSON data from file and convert to dictionary\n", |
| 250 | + " print(\"Data loaded from 'data.json':\", loaded_data)" |
| 251 | + ] |
| 252 | + }, |
| 253 | + { |
| 254 | + "cell_type": "markdown", |
| 255 | + "id": "6b4a1fbe", |
| 256 | + "metadata": {}, |
| 257 | + "source": [ |
| 258 | + "#### 6. Handling File Exceptions\n", |
| 259 | + "\n", |
| 260 | + "Sometimes, errors occur while working with files. For example:\n", |
| 261 | + "- The file does not exist.\n", |
| 262 | + "- The program lacks permission to read/write.\n", |
| 263 | + "- The file is already in use by another program.\n", |
| 264 | + "\n", |
| 265 | + "To handle these issues, we can use the `try-except` block to catch and handle file-related exceptions.\n", |
| 266 | + "\n", |
| 267 | + "##### Example: Handling File Not Found and Permission Errors\n" |
| 268 | + ] |
| 269 | + }, |
| 270 | + { |
| 271 | + "cell_type": "code", |
| 272 | + "execution_count": 12, |
| 273 | + "id": "98796842", |
| 274 | + "metadata": {}, |
| 275 | + "outputs": [ |
| 276 | + { |
| 277 | + "name": "stdout", |
| 278 | + "output_type": "stream", |
| 279 | + "text": [ |
| 280 | + "Error: The file does not exist!\n" |
| 281 | + ] |
| 282 | + } |
| 283 | + ], |
| 284 | + "source": [ |
| 285 | + "try:\n", |
| 286 | + " with open('non_existent_file.txt', 'r') as file:\n", |
| 287 | + " content = file.read()\n", |
| 288 | + " print(content)\n", |
| 289 | + "\n", |
| 290 | + "except FileNotFoundError:\n", |
| 291 | + " print(\"Error: The file does not exist!\")\n" |
| 292 | + ] |
| 293 | + } |
| 294 | + ], |
| 295 | + "metadata": { |
| 296 | + "kernelspec": { |
| 297 | + "display_name": "Python 3", |
| 298 | + "language": "python", |
| 299 | + "name": "python3" |
| 300 | + }, |
| 301 | + "language_info": { |
| 302 | + "codemirror_mode": { |
| 303 | + "name": "ipython", |
| 304 | + "version": 3 |
| 305 | + }, |
| 306 | + "file_extension": ".py", |
| 307 | + "mimetype": "text/x-python", |
| 308 | + "name": "python", |
| 309 | + "nbconvert_exporter": "python", |
| 310 | + "pygments_lexer": "ipython3", |
| 311 | + "version": "3.10.16" |
| 312 | + } |
| 313 | + }, |
| 314 | + "nbformat": 4, |
| 315 | + "nbformat_minor": 5 |
| 316 | +} |
0 commit comments