Python18 min read

Python File Handling

Learn how to read, write, append, and handle file errors using best-practice patterns with clear outputs.

Emily Davis
August 22, 2025
7.2k178

File handling lets your program store information outside the program run. This is how apps create logs, save reports, and manage data files.

The most important rule: use `with` so the file closes automatically.

## Write to a file

```python
with open("notes.txt", "w") as file:
    file.write("Hello from San Diego!")
```

Now `notes.txt` exists and contains one line.

## Read the file

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

print(content)
```

Expected output:

```
Hello from San Diego!
```

## Append to the file

```python
with open("notes.txt", "a") as file:
    file.write("\nNew line added!")
```

Read again:

```python
with open("notes.txt", "r") as file:
    print(file.read())
```

Expected output:

```
Hello from San Diego!
New line added!
```

## Read line by line (best for large files)

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

Expected output:

```
Hello from San Diego!
New line added!
```

## Handling missing file error

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

Expected output:

```
The file does not exist.
```

## Graph: safe file workflow

```mermaid
flowchart TD
  A[Open with 'with'] --> B{File exists?}
  B -->|Yes| C[Read/Write]
  B -->|No| D[Handle error]
  C --> E[Auto close]
  D --> E[Auto close]
```

In the next lesson, you will start intermediate Python with list comprehensions, which help you write cleaner data transformations.
#Python#Beginner#Files