DEV Community

Cover image for Day 41/100: Reading Files with open() in Python
 Rahul Gupta
Rahul Gupta

Posted on

Day 41/100: Reading Files with open() in Python

Welcome to Day 41 of your Python journey!
Working with files is a core skill for any developer. Whether you're handling logs, reading configurations, or processing data, Python’s built-in open() function makes it simple and powerful.

Today, we’ll learn how to read files safely and efficiently using open().


πŸ“₯ 1. The open() Function Basics

The syntax is:

file = open("filename.txt", "mode")
Enter fullscreen mode Exit fullscreen mode
  • "r" – Read mode (default)
  • "w" – Write mode (overwrites file)
  • "a" – Append mode
  • "b" – Binary mode (use with images, etc.)
  • "t" – Text mode (default)

Always remember to close files when done:

file = open("sample.txt", "r")
content = file.read()
file.close()
Enter fullscreen mode Exit fullscreen mode

πŸ“„ 2. Reading the Whole File

with open("sample.txt", "r") as f:
    data = f.read()
    print(data)
Enter fullscreen mode Exit fullscreen mode

βœ… Using with automatically closes the file, even if an error occurs.


πŸ“œ 3. Reading Line by Line

readline() – Reads one line at a time:

with open("sample.txt", "r") as f:
    line = f.readline()
    while line:
        print(line.strip())
        line = f.readline()
Enter fullscreen mode Exit fullscreen mode

readlines() – Returns all lines as a list:

with open("sample.txt", "r") as f:
    lines = f.readlines()
    print(lines)
Enter fullscreen mode Exit fullscreen mode

πŸ“ 4. Reading Fixed Amount of Characters

with open("sample.txt", "r") as f:
    first_10_chars = f.read(10)
    print(first_10_chars)
Enter fullscreen mode Exit fullscreen mode

πŸ”„ 5. Iterating Over a File Object

You can loop through a file directly:

with open("sample.txt", "r") as f:
    for line in f:
        print(line.strip())
Enter fullscreen mode Exit fullscreen mode

This is memory-efficient for large files because it reads line by line.


🧨 6. Handling Errors Safely

Always handle exceptions when dealing with files:

try:
    with open("non_existent.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found!")
except IOError:
    print("Error reading file!")
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Real-World Example: Count Words in a File

with open("sample.txt", "r") as f:
    text = f.read()
    words = text.split()
    print("Total Words:", len(words))
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Summary

  • Use open(filename, "r") to read files.
  • Always close files or use with open() for safety.
  • read(), readline(), and readlines() give you flexibility.
  • Handle errors with try-except.
  • Iterating over file objects is memory-efficient for large files.

πŸ§ͺ Practice Challenge

  1. Read a file and count:
  • Total lines
  • Total words
  • Total characters
    1. Write a script to read a large log file and only print lines containing the word "ERROR".
    2. Read a file and reverse the order of its lines before printing.

Top comments (0)