Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Direct access of a line in a file

names = ['Foo', 'Bar', 'Baz']
for name in names:
    print(name)
print(names[1])

Output:

Foo
Bar
Baz
Bar
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.

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