Direct access of a line in a file



examples/files/access_list_element.py
names = ['Foo', 'Bar', 'Baz']
for name in names:
    print(name)
print(names[1])

Foo
Bar
Baz
Bar


examples/files/fh_access.py
import sys
if len(sys.argv) != 2:
    exit(f"Run {sys.argv[0]} FILENAME")

filename = sys.argv[1]

# We can iterate over the lines
#with open(filename, 'r') as fh:
#    for line in fh:
#        print(line)

# We cannot access an element
with open(filename, 'r') as fh:
    print(fh[2])

Traceback (most recent call last):
  File "examples/files/fh_access.py", line 14, in <module>
    print(fh[2])
TypeError: '_io.TextIOWrapper' object is not subscriptable

This does NOT work because files can only be accessed sequentially.

examples/files/read_all_lines.py
import sys
if len(sys.argv) != 2:
    exit(f"Run {sys.argv[0]} FILENAME")

filename = sys.argv[1]

with open(filename, 'r') as fh:
    rows = fh.readlines()
print(rows[2])

examples/files/count_lines.py
import sys
if len(sys.argv) != 2:
    exit(f"Run {sys.argv[0]} FILENAME")

filename = sys.argv[1]

with open(filename, 'r') as fh:
    count = 0
    for row in fh:
        if count == 2:
            break
        count += 1
print(row)