Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 08 / Topic 1 of 10

Opening files with with open(...)

A file must be opened, used, then closed, like a cupboard: open it, take or put things, close it. with closes it for you, even if an error happens. Always use with. open() gives you a file object (here called f): the handle you read from and write to.

Real-world example: save a shopping list.

with open("demo_shopping.txt", "w", encoding="utf-8") as f:
    f.write("Rice\n")
    f.write("Dal\n")

with open("demo_shopping.txt", encoding="utf-8") as f:
    print(f.read(), end="")   # end="": the file already ends with "\n"
# Rice
# Dal

print(f.closed)   # True  (closed automatically after the with block)

๐Ÿ” Going deeper: writes are buffered: Python collects them in memory and passes them on in chunks. Closing the file (or f.flush()) hands the data to the operating system, so other programs can now read it. But the OS may keep it in its own memory for a few seconds before it really reaches the disk; if the power goes off in that moment, it can still be lost. For data that must survive a crash, call os.fsync(f.fileno()) after f.flush() (inside the with block): it waits until the OS has written the file to the disk. with guarantees the close, even when an exception is raised inside the block.

Done here? The practice set for Part 8 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide