|
| 1 | +# 📁 File Handling in Python |
| 2 | + |
| 3 | +File handling in Python allows us to **create**, **read**, **write**, and **delete** files. It’s used to manage data stored in files (like `.txt`, `.csv`, etc.). |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## 📝 Types of Files |
| 8 | + |
| 9 | +There are mainly **two types** of files: |
| 10 | + |
| 11 | +1. **Text Files** – contain readable characters (e.g., `.txt`, `.csv`, `.py`) |
| 12 | +2. **Binary Files** – contain non-readable (binary) data (e.g., images, videos, `.exe`, `.dat`) |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +## ⚙️ File Handling Modes |
| 17 | + |
| 18 | +| Mode | Description | |
| 19 | +|------|-------------| |
| 20 | +| `'r'` | Read (default) – error if file doesn’t exist | |
| 21 | +| `'w'` | Write – creates new file or overwrites existing | |
| 22 | +| `'a'` | Append – adds content to end of file | |
| 23 | +| `'x'` | Create – error if file already exists | |
| 24 | +| `'b'` | Binary mode (e.g., `rb`, `wb`) | |
| 25 | +| `'t'` | Text mode (default, e.g., `rt`, `wt`) | |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +## ✅ Basic Operations |
| 30 | + |
| 31 | +### 1. **Open a File** |
| 32 | + |
| 33 | +```python |
| 34 | +file = open("example.txt", "r") # Open for reading |
| 35 | + |
| 36 | +#Or using with (recommended – auto closes file): |
| 37 | +with open("example.txt", "r") as file: |
| 38 | + data = file.read() |
| 39 | + |
| 40 | +``` |
| 41 | + |
| 42 | +### 🔧 Common File Operations |
| 43 | + |
| 44 | +Below are the most commonly used file operations in Python, including reading, writing, closing, and deleting a file: |
| 45 | + |
| 46 | +```python |
| 47 | +# 📖 Read from a file |
| 48 | +with open("example.txt", "r") as file: |
| 49 | + content = file.read() # Reads the full content |
| 50 | + # line = file.readline() # Reads the first line |
| 51 | + # lines = file.readlines() # Reads all lines into a list |
| 52 | + |
| 53 | +# ✍️ Write to a file |
| 54 | +with open("example.txt", "w") as file: |
| 55 | + file.write("Hello, world!") # Overwrites the file if it exists |
| 56 | + |
| 57 | +# ❌ Close the file (only needed if not using 'with' statement) |
| 58 | +file = open("example.txt", "r") |
| 59 | +# ... some operations ... |
| 60 | +file.close() |
| 61 | + |
| 62 | +# 🗑️ Delete a file |
| 63 | +import os |
| 64 | + |
| 65 | +if os.path.exists("example.txt"): |
| 66 | + os.remove("example.txt") |
| 67 | +else: |
| 68 | + print("File does not exist.") |
| 69 | + |
| 70 | + |
| 71 | + |
0 commit comments