|
1 |
| -fin = open('../../README.md') # Use the default mode: rt = read + text |
| 1 | +# SPDX-License-Identifier: BSD-3-Clause |
| 2 | + |
| 3 | +fin = open("../../README.md") # Use the default mode: rt = read + text |
2 | 4 |
|
3 | 5 | # Use the readline function to, well... read one line from the opened file.
|
4 | 6 | line = fin.readline()
|
5 |
| -print(line, end='') # The line we've just read already contains a trailing \n. |
| 7 | +print(line, end="") # The line we've just read already contains a trailing \n. |
6 | 8 |
|
7 | 9 | # The file object (f) maintains an internal cursor, which is an offset from the
|
8 | 10 | # beginning of the file, where the next operation (read/write) will take place.
|
9 | 11 | # For this reason, the next calls to readline return the correct lines in the
|
10 | 12 | # file.
|
11 |
| -print(fin.readline(), end='') # Second line is empty |
12 |
| -print(fin.readline(), end='') # Third line |
| 13 | +print(fin.readline(), end="") # Second line is empty |
| 14 | +print(fin.readline(), end="") # Third line |
13 | 15 |
|
14 | 16 | # There are situations where it is necessary to move the cursor ourselves.
|
15 | 17 | # For this, we have the the seek function.
|
16 | 18 | # First, let's see where our cursor is now.
|
17 |
| -print(f'fin cursor is initially at {fin.tell()} bytes') |
| 19 | +print(f"fin cursor is initially at {fin.tell()} bytes") |
18 | 20 |
|
19 | 21 | # The seek function takes 2 parameters:
|
20 | 22 | # - offset: The number of bytes to move the cursor. Can be negative to move the cursor back
|
|
23 | 25 | # - 1: from the cursor's current position
|
24 | 26 | # - 2: from the end of the file.
|
25 | 27 | fin.seek(0, 0) # Move the cursor to the beginning of the file
|
26 |
| -print(f'after fin.seek(0, 0), fin cursor is at {fin.tell()} bytes') |
| 28 | +print(f"after fin.seek(0, 0), fin cursor is at {fin.tell()} bytes") |
27 | 29 | # Let's try to read a line and see if it truly is the first.
|
28 |
| -print('First line of README.md:', fin.readline(), end='') # It is. |
| 30 | +print("First line of README.md:", fin.readline(), end="") # It is. |
29 | 31 |
|
30 | 32 | # The other modes are available only when opening the file in binary mode.
|
31 | 33 | # We will do this in the next section.
|
32 | 34 |
|
33 | 35 | # It's good practice to close a file when you no longer use it.
|
34 | 36 | fin.close()
|
35 | 37 |
|
36 |
| -fout = open('output.txt', 'w') # Open output.txt for writing text |
| 38 | +fout = open("output.txt", "w") # Open output.txt for writing text |
37 | 39 | # Unlike print, write does not add a \n character at the end of our text.
|
38 |
| -fout.write('This is the first line in output.txt\n') |
39 |
| -fout.write('SSS Rulz!\n') |
| 40 | +fout.write("This is the first line in output.txt\n") |
| 41 | +fout.write("SSS Rulz!\n") |
40 | 42 |
|
41 | 43 | fout.close()
|
0 commit comments