You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lectures/python_essentials.md
+25-16Lines changed: 25 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -326,31 +326,40 @@ out
326
326
print(out)
327
327
```
328
328
329
-
We can also use `with` statement to contain operations on the file within a block for clarity and cleanness.
329
+
We can also use a `with` statement (also known as a [context manager](https://realpython.com/python-with-statement/#the-with-statement-approach)) which enables you to group operations on the file within a block which improves the clarity of your code.
330
330
331
-
```{code-cell} python3
332
-
with open('newfile.txt', 'a+') as file:
333
-
334
-
# Adding a line at the end
335
-
file.write('\nAdding a new line')
336
331
337
-
# Move the pointer back to the top
338
-
file.seek(0)
339
-
340
-
# Read the file line-by-line from the first line
332
+
```{code-cell} python3
333
+
with open("newfile.txt", "r") as f:
334
+
file = f.readlines()
335
+
with open("output.txt", "w") as fo:
341
336
for i, line in enumerate(file):
342
-
print(f'Line {i}: {line}')
337
+
fo.write(f'Line {i}: {line} \n')
343
338
```
344
339
345
-
Note that we used `a+` mode (standing for append+ mode) to allow appending new content at the end of the file and enable reading at the same time.
340
+
```{code-cell} python3
341
+
fo = open('output.txt', 'r')
342
+
out = fo.read()
343
+
print(out)
344
+
```
346
345
347
-
There are [many modes](https://www.geeksforgeeks.org/reading-writing-text-files-python/) you could set when opening the file.
346
+
We can write the example above under the same context to reduce redundancy
348
347
349
-
When experimenting with different modes, it is important to check where the pointer is set.
348
+
```{code-cell} python3
349
+
with open("newfile.txt", "r") as f, open("output2.txt", "w") as fo:
350
+
for i, line in enumerate(f):
351
+
fo.write(f'Line {i}: {line} \n')
352
+
```
350
353
351
-
The pointer is set to the end of the file in `a+` mode.
354
+
```{code-cell} python3
355
+
fo = open('output2.txt', 'r')
356
+
out = fo.read()
357
+
print(out)
358
+
```
352
359
353
-
Here we set `file.seek(0)` to move the pointer back to the first line (line 0) of the file to print the whole file.
360
+
```{note}
361
+
Note that we only used `r` and `w` mode. There are [more modes](https://www.geeksforgeeks.org/reading-writing-text-files-python/) you could experiment with.
0 commit comments