TalentJR

Lesson 16

File Handling Basics

Read and write text files

1What is File Handling?✨

File handling in Python allows you to read from and write to files on your computer. This is essential for storing data, creating logs, or saving user information!

2Why Learn File Handling?🎯

  • ✓ Manage data efficiently
  • ✓ Create applications that store user preferences
  • ✓ Develop skills for real-world software development
  • ✓ Understand how data persists beyond program execution

3Opening a File💡

To read or write a file, you first need to open it. Use the `open()` function to access files.

4Example:🚀

💻 code
file = open("example.txt", "r") 

Here, "r" means you are opening the file for reading. You can also use "w" for writing or "a" for appending.

5Reading from a File🔍

Once the file is open, you can read its contents using methods like `read()`, `readline()`, or `readlines()`.

6Example:⭐

💻 code
content = file.read() 
print(content) 

This reads the entire file and stores it in the variable `content`.

7Writing to a File🧩

To write data to a file, open it in write mode ("w"). This will create a new file or overwrite an existing one.

8Example:🎈

💻 code
file = open("output.txt", "w") 
file.write("Hello, this is a test!") 
file.close() 

Don’t forget to close the file after writing to ensure all data is saved properly!

9Capstone Project: Creating a Simple To-Do List✨

Now that you know file handling, let's create a simple to-do list program. It will allow users to add tasks and save them to a file.

10Example:🎯

💻 code
def add_task(task):
    with open("tasks.txt", "a") as file:
        file.write(task + "\n")
💻 code
task = input("Enter a new task: ")
add_task(task)

This program asks for a task and appends it to a file named `tasks.txt`. Remember to test your program and check the file!

🎯 Practice Challenges

Master File Handling Basics by completing all 3 difficulty levels

🟢 EASY

File Handling Basics - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

File Handling Basics - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

File Handling Basics - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master File Handling Basics? 🚀

Complete the challenges, take the quiz and keep your learning streak going!