Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 7247d83

Browse filesBrowse files
committed
add with statement
1 parent 1c04305 commit 7247d83
Copy full SHA for 7247d83

File tree

Expand file treeCollapse file tree

1 file changed

+21
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+21
-0
lines changed
Open diff view settings
Collapse file

‎lectures/python_essentials.md‎

Copy file name to clipboardExpand all lines: lectures/python_essentials.md
+21Lines changed: 21 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.