šŸ“„ Python File Handling — Reading Files

Introduction 🌟

Reading files is one of the most fundamental operations in Python. Python provides simple and powerful methods to read text files, JSON, CSV, logs, configs, and more.

Note

šŸ’” Always remember to close files after use — or use with open() to do it automatically.

1. Opening a File for Reading šŸ“‚

You use the open() function:

open_file.py

file = open("data.txt", "r")  # 'r' = read mode
content = file.read()
print(content)
file.close()

Note

āœ” "r" = read mode (default)

2. Using with open() (Best Practice) 🧠

Using with automatically closes the file — even if errors occur.

with_open.py

with open("data.txt", "r") as file:
    content = file.read()
    print(content)

Note

āœ” Recommended for all file operations.

3. Reading Entire File at Once šŸ“–

read_all.py

with open("data.txt", "r") as file:
    data = file.read()
    print(data)

āœ” Useful for small files.

4. Reading File Line by Line šŸ“

read_line_by_line.py

with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

āœ” Efficient for large files
āœ” strip() removes newline characters

5. Reading All Lines into a List šŸ“

readlines.py

with open("data.txt", "r") as file:
    lines = file.readlines()
    print(lines)

āœ” Each line becomes an item in the list.

6. Reading a Specific Number of Characters āœ‚ļø

read_chars.py

with open("data.txt", "r") as file:
    chunk = file.read(10)  # read first 10 characters
    print(chunk)

7. Reading One Line at a Time Using readline() šŸ”

readline.py

with open("data.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()
    print(line1, line2)

8. Handling File Not Found Error āš ļø

file_not_found.py

try:
    with open("missing.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("āŒ File does not exist!")

9. Reading Binary Files (Images, Videos, PDFs) šŸ–¼ļø

binary_read.py

with open("image.png", "rb") as file:
    data = file.read()
    print("Bytes read:", len(data))

āœ” "rb" = read binary mode

10. Reading Files with Encoding (UTF-8, etc.) 🌐

encoding.py

with open("data.txt", "r", encoding="utf-8") as file:
    text = file.read()
    print(text)

11. Checking File Cursor Position šŸ“

tell_position.py

with open("data.txt", "r") as file:
    print(file.tell())   # cursor position
    file.read(5)
    print(file.tell())

12. Moving File Cursor Using seek() šŸŽ›ļø

seek_example.py

with open("data.txt", "r") as file:
    file.seek(0)      # move to start
    print(file.read(5))

13. Real-World Example: Counting Lines šŸ“Š

count_lines.py

count = 0
with open("log.txt", "r") as file:
    for _ in file:
        count += 1

print("Total lines:", count)

14. Real-World Example: Searching Text šŸ”

search_text.py

with open("notes.txt", "r") as file:
    for line in file:
        if "error" in line:
            print("Found:", line.strip())

15. Real-World Example: Reading Config Files āš™ļø

config_read.py

settings = {}

with open("config.txt", "r") as file:
    for line in file:
        key, value = line.strip().split("=")
        settings[key] = value

print(settings)

Best Practices šŸ’”

  • āœ” Always use with open() to avoid forgetting close()
  • āœ” Handle exceptions for missing or locked files
  • āœ” Avoid reading huge files into memory at once
  • āœ” Use readline() or loops for large text files

Conclusion šŸŽ‰

>>ā€œReading files is the gateway to data — logs, configs, documents, scripts, everything.ā€ ✨

You now fully understand how to Read Files in Python! Want the next topic? Try Write Files, Append Files, File Modes, or JSON Handling. Just tell me! 😊