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
+19-13Lines changed: 19 additions & 13 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -326,27 +326,33 @@ 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.
330
-
331
-
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.
332
-
333
-
There are even [more modes](https://www.geeksforgeeks.org/reading-writing-text-files-python/) you could set when openning the file.
334
-
335
-
The trick is to check where the pointer is set: if the pointer is set at the end of the file `seek` method is needed to go back to the start of the file.
336
-
337
-
Here we set `file.seek(0)` to move the pointer back to the first line (line 0) of the file.
329
+
We can also use `with` statement to contain operations on the file within a block for clarity and cleanness.
338
330
339
331
```{code-cell} python3
340
332
with open('newfile.txt', 'a+') as file:
333
+
334
+
# Adding a line at the end
341
335
file.write('\nAdding a new line')
336
+
337
+
# Move the pointer back to the top
342
338
file.seek(0)
343
-
lines = file.readlines()
344
-
i = 0
345
-
for line in lines:
339
+
340
+
# Read the file line-by-line from the first line
341
+
for i, line in enumerate(file):
346
342
print(f'Line {i}: {line}')
347
-
i += 1
348
343
```
349
344
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.
346
+
347
+
There are [many modes](https://www.geeksforgeeks.org/reading-writing-text-files-python/) you could set when opening the file.
348
+
349
+
When experimenting with different modes, it is important to check where the pointer is set.
350
+
351
+
The pointer is set to the end of the file in `a+` mode.
352
+
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.
0 commit comments