|
| 1 | +--- |
| 2 | +id: python-io |
| 3 | +title: File Input and Output (I/O) in Python |
| 4 | +description: Learn how to read from and write to files using Python's built-in I/O functions. |
| 5 | +sidebar_label: File I/O in Python |
| 6 | +sidebar_position: 13 |
| 7 | +tags: |
| 8 | + [ |
| 9 | + Python, |
| 10 | + List in Python, |
| 11 | + Introduction of python, |
| 12 | + Python Syntax, |
| 13 | + Variables, |
| 14 | + Operators, |
| 15 | + Type Casting, |
| 16 | + String, |
| 17 | + Tuple in Python |
| 18 | + Array in Python |
| 19 | + Functions in Python |
| 20 | + Recursion in Python |
| 21 | + Opps in Python |
| 22 | + ] |
| 23 | +--- |
| 24 | + |
| 25 | +# File Input and Output (I/O) in Python |
| 26 | + |
| 27 | +In Python, file I/O is used to read from or write to files. This is an essential part of any programming language when it comes to data processing, logging, or configuration. |
| 28 | + |
| 29 | + |
| 30 | +## Opening Files |
| 31 | + |
| 32 | +To work with files in Python, you use the built-in `open()` function. |
| 33 | + |
| 34 | +```python |
| 35 | +file = open("example.txt", "r") # Open for reading |
| 36 | +```` |
| 37 | + |
| 38 | +### Modes: |
| 39 | + |
| 40 | +| Mode | Description | |
| 41 | +| ----- | ---------------------------------------------------- | |
| 42 | +| `'r'` | Read (default). Fails if the file doesn’t exist. | |
| 43 | +| `'w'` | Write. Creates a new file or truncates existing one. | |
| 44 | +| `'a'` | Append. Adds content to the end of the file. | |
| 45 | +| `'b'` | Binary mode. Used with `'rb'`, `'wb'`, etc. | |
| 46 | +| `'x'` | Create. Fails if the file already exists. | |
| 47 | + |
| 48 | + |
| 49 | +## Reading from a File |
| 50 | + |
| 51 | +### `read()` – Reads entire content |
| 52 | + |
| 53 | +````python |
| 54 | +with open("example.txt", "r") as file: |
| 55 | + content = file.read() |
| 56 | + print(content) |
| 57 | +```` |
| 58 | + |
| 59 | +### `readline()` – Reads one line at a time |
| 60 | + |
| 61 | +````python |
| 62 | +with open("example.txt", "r") as file: |
| 63 | + line = file.readline() |
| 64 | + print(line) |
| 65 | +```` |
| 66 | + |
| 67 | +### `readlines()` – Reads all lines into a list |
| 68 | + |
| 69 | +````python |
| 70 | +with open("example.txt", "r") as file: |
| 71 | + lines = file.readlines() |
| 72 | + print(lines) |
| 73 | +```` |
| 74 | + |
| 75 | +## Writing to a File |
| 76 | + |
| 77 | +### `write()` – Write string to file |
| 78 | + |
| 79 | +````python |
| 80 | +with open("output.txt", "w") as file: |
| 81 | + file.write("Hello, world!") |
| 82 | +```` |
| 83 | + |
| 84 | +### `writelines()` – Write list of strings |
| 85 | + |
| 86 | +````python |
| 87 | +lines = ["Line 1\n", "Line 2\n"] |
| 88 | +with open("output.txt", "w") as file: |
| 89 | + file.writelines(lines) |
| 90 | +```` |
| 91 | + |
| 92 | + |
| 93 | +## Using `with` Statement (Best Practice) |
| 94 | + |
| 95 | +The `with` block ensures the file is automatically closed after use: |
| 96 | + |
| 97 | +````python |
| 98 | +with open("data.txt", "r") as file: |
| 99 | + data = file.read() |
| 100 | +```` |
| 101 | + |
| 102 | +This is the **recommended way** to handle files in Python. |
| 103 | + |
| 104 | + |
| 105 | +## Error Handling in File I/O |
| 106 | + |
| 107 | +Always handle file operations with care to avoid exceptions: |
| 108 | + |
| 109 | +````python |
| 110 | +try: |
| 111 | + with open("config.txt", "r") as file: |
| 112 | + config = file.read() |
| 113 | +except FileNotFoundError: |
| 114 | + print("File not found.") |
| 115 | +except IOError: |
| 116 | + print("Error while handling the file.") |
| 117 | +```` |
| 118 | + |
| 119 | + |
| 120 | +## File Paths |
| 121 | + |
| 122 | +You can also handle file paths using the `os` or `pathlib` module: |
| 123 | + |
| 124 | +````python |
| 125 | +from pathlib import Path |
| 126 | + |
| 127 | +file_path = Path("docs") / "myfile.txt" |
| 128 | +with open(file_path, "r") as file: |
| 129 | + print(file.read()) |
| 130 | +```` |
| 131 | + |
| 132 | + |
| 133 | +## Example: Reading & Writing |
| 134 | + |
| 135 | +````python |
| 136 | +# Write to a file |
| 137 | +with open("sample.txt", "w") as file: |
| 138 | + file.write("This is a test.") |
| 139 | + |
| 140 | +# Read the file |
| 141 | +with open("sample.txt", "r") as file: |
| 142 | + print(file.read()) |
| 143 | +```` |
| 144 | + |
| 145 | + |
| 146 | +## Summary |
| 147 | + |
| 148 | +* Use `open()` to access files. |
| 149 | +* Use `read()`, `readline()`, or `readlines()` to read. |
| 150 | +* Use `write()` or `writelines()` to write. |
| 151 | +* Always use `with` to handle files safely. |
| 152 | +* Handle exceptions for robustness. |
0 commit comments