Labs ICT
โญ Pro Login

File Handling

File Modes with open()

The open() function returns a file object. The second argument is the mode: "r" (read), "w" (write, overwrites), "a" (append), "x" (exclusive creation). Always close files when done.

f = open("example.txt", "w")
f.write("Hello, file!")
f.close()

f = open("example.txt", "r")
content = f.read()
f.close()
print(content)
Try it Yourself โ†’

The with Statement

The with statement automatically closes the file, even if an error occurs. It's the safest and most readable way to work with files.

with open("example.txt", "w") as f:
    f.write("No need to close manually!")

with open("example.txt", "r") as f:
    print(f.read())
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does the 'with' statement do when opening files?