|
| 1 | +# Python File Handling |
| 2 | + |
| 3 | +**Video link:** |
| 4 | + |
| 5 | +In this video, we learned how to perform various file operations like reading and writing into files with the help examples. |
| 6 | + |
| 7 | +**Programs in the Video** |
| 8 | + |
| 9 | +- [File Operations](#file-operations) |
| 10 | +- [Opening a File](#opening-a-file) |
| 11 | +- [Reading files in Python](#reading-files-in-python) |
| 12 | +- [Exception Handling with Files](#exception-handling-with-files) |
| 13 | +- [Writing to files in Python](#writing-to-files-in-python) |
| 14 | +- [Appending to files in Python](#appending-to-files-in-python) |
| 15 | +- [Python `readlines()` and `writelines()`](#python-readlines-and-writelines) |
| 16 | + |
| 17 | +--- |
| 18 | + |
| 19 | +## File Operations |
| 20 | +Files are named locations on our storage device for recording data. Python provides numerous builtin functions to work with these files. |
| 21 | + |
| 22 | +There are three steps we need to follow to work with files: |
| 23 | + |
| 24 | +- Open a file |
| 25 | +- Perform Operation (Read or Write) |
| 26 | +- Close the file |
| 27 | + |
| 28 | +--- |
| 29 | + |
| 30 | +## Opening a File |
| 31 | + |
| 32 | +In Python, we use the builtin `open()` function to open files. |
| 33 | + |
| 34 | +Suppose we have a file called `message.txt` with the following content: |
| 35 | +``` |
| 36 | +I love programming. |
| 37 | +I love Programiz. |
| 38 | +``` |
| 39 | + |
| 40 | +We can open it using: |
| 41 | + |
| 42 | +```python |
| 43 | +f = open('message.txt') |
| 44 | +``` |
| 45 | + |
| 46 | +The `open()` function is opening the file which returns a file object that can be used to perform file operations. |
| 47 | + |
| 48 | +By default, the file will be opened in the read mode. We could also have used: |
| 49 | + |
| 50 | +```python |
| 51 | +# read mode |
| 52 | +f = open('message.txt', 'r') |
| 53 | + |
| 54 | +# write mode |
| 55 | +f = open('message.txt', 'w') |
| 56 | +``` |
| 57 | + |
| 58 | +|Mode|Description| |
| 59 | +|---|---| |
| 60 | +|`r` (Read Mode)|Opens a file for reading (default)| |
| 61 | +|`w` (Write Mode)|Opens a file for writing, Creates a new file if it does not exist, Clears the content of the file if it exists| |
| 62 | +|`a` (Append Mode)|Opens a file for appending at the end of the file, Creates a new file if it does not exist| |
| 63 | + |
| 64 | +--- |
| 65 | + |
| 66 | +## Reading files in Python |
| 67 | + |
| 68 | +After opening a file, we can read its contents using the `read()` method of the file object. |
| 69 | + |
| 70 | +```python |
| 71 | +f = open('message.txt', 'r') |
| 72 | + |
| 73 | +content = f.read() |
| 74 | +print(content) |
| 75 | + |
| 76 | +f.close() |
| 77 | +``` |
| 78 | + |
| 79 | +**Output** |
| 80 | +``` |
| 81 | +I love programming. |
| 82 | +I love Programiz. |
| 83 | +``` |
| 84 | + |
| 85 | +>**Note**: We should always close the file using `close()` method after working with files. It is a good programming practice. |
| 86 | +
|
| 87 | +It is also possible to read only a certain number of characters from a file using the `read()` method. |
| 88 | +For this, we pass an optional `size` argument. |
| 89 | + |
| 90 | +Let's read only the first 6 characters: |
| 91 | + |
| 92 | +```python |
| 93 | +f = open('message.txt', 'r') |
| 94 | + |
| 95 | +content = f.read(6) |
| 96 | +print(content) |
| 97 | + |
| 98 | +f.close() |
| 99 | +``` |
| 100 | + |
| 101 | +**Output** |
| 102 | +``` |
| 103 | +I love |
| 104 | +``` |
| 105 | + |
| 106 | +Now if we read the same file again, it starts reading from the 7th character because we have already read upto the 6th character. |
| 107 | + |
| 108 | +```python |
| 109 | +f = open('message.txt', 'r') |
| 110 | + |
| 111 | +content = f.read(6) |
| 112 | +print(content) |
| 113 | + |
| 114 | +more_content = f.read(12) |
| 115 | +print(more_content) |
| 116 | + |
| 117 | +f.close() |
| 118 | +``` |
| 119 | + |
| 120 | +**Output** |
| 121 | +``` |
| 122 | +I love |
| 123 | + programming |
| 124 | +``` |
| 125 | + |
| 126 | +--- |
| 127 | + |
| 128 | +## Exception Handling with Files |
| 129 | + |
| 130 | +We might encounter unexpected errors while working with external files. |
| 131 | +So, it's a good practice to open files using the `try...finally` statement. |
| 132 | + |
| 133 | +```python |
| 134 | +try: |
| 135 | + f = open('message.txt', 'r') |
| 136 | + |
| 137 | + content = f.read(6) |
| 138 | + print(content) |
| 139 | + |
| 140 | + more_content = f.read(12) |
| 141 | + print(more_content) |
| 142 | +finally: |
| 143 | + f.close() |
| 144 | +``` |
| 145 | + |
| 146 | +Now, even if our program encounters an error, our file will be closed. It is because the `finally` block always gets executed. |
| 147 | + |
| 148 | +There is even a better way to write this same code in Python using the `with...open` syntax. |
| 149 | + |
| 150 | + |
| 151 | +```python |
| 152 | +with open('message.txt', 'r') as f: |
| 153 | + content = f.read(6) |
| 154 | + print(content) |
| 155 | + |
| 156 | + more_content = f.read(12) |
| 157 | + print(more_content) |
| 158 | +``` |
| 159 | +>**Note**: It is highly recommended to use this syntax while working with files because we don't need to explicitly call the `close()` method |
| 160 | +> and our code becomes much cleaner than before. |
| 161 | +
|
| 162 | +--- |
| 163 | + |
| 164 | +## Writing to files in Python |
| 165 | + |
| 166 | +To write content to a file, we must first open it in write mode. Then, we can start writing content to it using the `write()` method. |
| 167 | + |
| 168 | +There are two things you need to remember while writing to a file: |
| 169 | + |
| 170 | +- If you try to open a file that doesn't exist, a new file is automatically created. |
| 171 | +- If a file already exists, its contents are removed, and our new content is added to it. |
| 172 | + |
| 173 | + |
| 174 | +```python |
| 175 | +with open('python.txt', 'w') as f: |
| 176 | + f.write("Python is awesome") |
| 177 | + f.write("I love Python") |
| 178 | +``` |
| 179 | + |
| 180 | +A `python.txt` file is created in the same directory with the following content: |
| 181 | + |
| 182 | +``` |
| 183 | +Python is awesomeI love Python |
| 184 | +``` |
| 185 | + |
| 186 | +To add a new line, we can use `\n`: |
| 187 | + |
| 188 | +```python |
| 189 | +with open('python.txt', 'w') as f: |
| 190 | + f.write("Python is awesome\n") |
| 191 | + f.write("I love Python") |
| 192 | +``` |
| 193 | + |
| 194 | +The `python.txt` file now has: |
| 195 | + |
| 196 | +``` |
| 197 | +Python is awesome |
| 198 | +I love python |
| 199 | +``` |
| 200 | + |
| 201 | +Notice that while running this program for the second time, the `python.txt` file was already created. |
| 202 | +Since opening an existing file in write mode will overwrite the file, all the previous data was erased and new content was written again. |
| 203 | + |
| 204 | +>**Note**: Be careful while using the write mode because you may accidentally erase the old data without realizing it. |
| 205 | +
|
| 206 | +--- |
| 207 | + |
| 208 | +## Appending to Files in Python |
| 209 | + |
| 210 | +We use this mode if we want to add additional data to the end of the file without erasing our previous data. |
| 211 | + |
| 212 | +Let's add an additional line to the previous `python.txt` file. |
| 213 | + |
| 214 | +```python |
| 215 | +with open('python.txt', 'a') as f: |
| 216 | + f.write("\nPython is my first programming language.") |
| 217 | +``` |
| 218 | + |
| 219 | +Contents of `python.txt`: |
| 220 | + |
| 221 | +``` |
| 222 | +Python is awesome |
| 223 | +I love Python |
| 224 | +Python is my first programming language. |
| 225 | +``` |
| 226 | + |
| 227 | +--- |
| 228 | + |
| 229 | +## Python `readlines()` and `writelines()` |
| 230 | + |
| 231 | +The `readlines()` method returns a list containing each line of the file. |
| 232 | + |
| 233 | +Let's open the same python.txt file we have been working on in read mode and use `readlines()`: |
| 234 | + |
| 235 | +```python |
| 236 | +with open('python.txt', 'r') as f: |
| 237 | + lines = f.readlines() |
| 238 | +print(lines) |
| 239 | +``` |
| 240 | + |
| 241 | +**Output** |
| 242 | + |
| 243 | +``` |
| 244 | +['Python is awesome\n', 'I love Python\n', 'Python is my first programming language.'] |
| 245 | +``` |
| 246 | + |
| 247 | +Similarly, there is also a `writelines()` method to write multiple items into a file. It writes the items of a list to the file. |
| 248 | + |
| 249 | +```python |
| 250 | +with open('javascript.txt', 'w') as f: |
| 251 | + lines = ['JS is also awesome', '\nJS is my second programming language.'] |
| 252 | + f.writelines(lines) |
| 253 | +``` |
| 254 | + |
| 255 | +A new file named `javascript.txt` is created with the following contents: |
| 256 | + |
| 257 | +``` |
| 258 | +JS is also awesome |
| 259 | +JS is my second programming language. |
| 260 | +``` |
0 commit comments