Labs ICT
โญ Pro Login

File Handling

1 min read | Python Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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)

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

๐Ÿงช Quick Quiz

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