GitHub

Original file line numberDiff line numberDiff line change

@@ -326,27 +326,33 @@ 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.

329+

We can also use `with` statement to contain operations on the file within a block for clarity and cleanness.

338330
339331

```{code-cell} python3

340332

with open('newfile.txt', 'a+') as file:

333+
334+

# Adding a line at the end

341335

file.write('\nAdding a new line')

336+
337+

# Move the pointer back to the top

342338

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):

346342

print(f'Line {i}: {line}')

347-

i += 1

348343

```

349344
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.

354+
355+
350356

### Paths

351357
352358

```{index} single: Python; Paths

Read the original on github.com ↗