Labs ICT
๐ŸŽ“ SIWES/IT Login

File Handling

1 min read | Python Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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?