Lesson 34 of 4085%

(Progress persistence is disabled until Phase 9)

Python
Intermediate

File Handling

Read from and write to files on your computer.

File Handling

What You’ll Learn

You’ll learn how to open, read, and write files using Python.

The open() Function

The key function for working with files in Python is the open() function. It takes two parameters: filename and mode.

Modes:

  • "r" - Read (Default)
  • "a" - Append (Adds to the end of the file)
  • "w" - Write (Overwrites the file)

Reading a File

# Assuming we have a file "demo.txt"
f = open("demo.txt", "r")
print(f.read())
f.close() # Always close your files!

The with Statement (Best Practice)

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed automatically, even if an exception is raised!

with open("demo.txt", "r") as f:
    content = f.read()
    print(content)
# No need to call f.close(), it's done automatically

Writing to a File

with open("demo.txt", "w") as f:
    f.write("Woops! I have deleted the content and added this instead!")

Lesson Progress

Take QuizBuild a Python Project