SwadhyAI Notes

All Python notes

Python Read Files 📖

Reading File Content

Python provides several methods to read content from a file. Always ensure the file exists before trying to read it to avoid errors.

📺 Analogy: Streaming vs Downloading

- read() is like Downloading the whole movie at once. It uses a lot of memory (RAM) if the file is huge.
- Line by Line is like Streaming. You process one scene (line) at a time, keeping memory usage low.

✨ Read Entire File

The read() method returns the entire text of the file.

python
with open("demofile.txt", "r") as f:
    print(f.read())

📜 Read Line by Line

You can read one line at a time using readline() or loop through the file object.

python
with open("demofile.txt", "r") as f:
    for line in f:
        print(line.strip()) # strip() removes the newline character

🎯 Real-World Application: Config Files

Reading configuration files line by line to find settings.

python
config = {}
with open("settings.conf", "r") as f:
    for line in f:
        if "=" in line:
            key, value = line.strip().split("=")
            config[key] = value

print(config) # {'theme': 'dark', 'version': '1.0'}

📋 Read All Lines into a List

The readlines() method returns a list containing each line in the file as a list item.

python
with open("demofile.txt", "r") as f:
    lines = f.readlines()

print(lines) # ['Hello\n', 'World\n']

⚠️ File Not Found

If you try to open a file that does not exist, Python will raise a FileNotFoundError. Use a try-except block to handle this.

python
try:
    with open("non_existent_file.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("The file does not exist!")