Failide lugemine „with“ abil

Faile saab lugeda kasutades with. See muudab failide töötlemise palju kergemaks, sest kõik failid, mis avatakse suletakse automaatselt. Lisaks muudab koodi lihtsamaks, sest erindeid ei pea püüdma try-finally blokkidega.

with open("test.txt") as f:     # Opens file with name of "test.txt"
    data = f.read()     # Reads all the lines from the file and saves it as a string.
print(f.closed)     # prints "True" to show that file has been closed.

Sama meetodi abil saab ka faili ridu ükshaaval läbi käia.

# Opens the file.
with open("testfile.txt") as f:

    # Loops over the file one line at a time.
    for line in f:
        # Prints the current line
        print(line)
# Prints "True" to show that the file has been closed
print(f.closed)