Skip to content

Commit 7247d83

Browse files
committed
add with statement
1 parent 1c04305 commit 7247d83

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

lectures/python_essentials.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,27 @@ out
326326
print(out)
327327
```
328328

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.
338+
339+
```{code-cell} python3
340+
with open('newfile.txt', 'a+') as file:
341+
file.write('\nAdding a new line')
342+
file.seek(0)
343+
lines = file.readlines()
344+
i = 0
345+
for line in lines:
346+
print(f'Line {i}: {line}')
347+
i += 1
348+
```
349+
329350
### Paths
330351

331352
```{index} single: Python; Paths

0 commit comments

Comments
 (0)