@@ -326,31 +326,40 @@ out
326326print(out)
327327```
328328329-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.
330330331-```{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')
336331337- # 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:
341336 for i, line in enumerate(file):
342- print(f'Line {i}: {line}')
337+ fo.write(f'Line {i}: {line} \n')
343338```
344339345-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+```
346345347-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
348347349-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+```
350353351-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+```
352359353-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.
362+```
354363355364356365### Paths