# Reading & Writing Files — Python Fundamentals: From Basics to Async

Source: https://www.skillbyai.com/en/python/py-file-basics

> Read and write text files safely with the with statement, line by line for large files, and learn context managers.

## The with statement

`with open(...) as f:` opens a file and **guarantees** it closes, even if an error happens inside the block.

```python
with open("notes.txt", "w") as f:
    f.write("Hello, file!\n")

with open("notes.txt", "r") as f:
    content = f.read()
    print(content)
```

## Reading line by line

Reading line by line keeps memory low for large files, since the file object is itself iterable.

```python
with open("notes.txt") as f:
    for line in f:
        print(line.strip())
```

## Context managers

`with` works because file objects are **context managers** — they define `__enter__`/`__exit__` so setup and cleanup happen automatically.
