DEV Community

Feddy Mwanjumwa
Feddy Mwanjumwa

Posted on AI-assisted

Python File Handling: How I Learned to Save Data Outside My Program

One thing I noticed while learning Python was that all the data I created disappeared when I stopped the program.

For example, I could create a list of contacts:

contacts = ["Amina", "Brian", "Feddy"]

It would work while the program was running, but once I closed it, the data was gone.

So I started wondering: how do I make Python save information?

That's where file handling came in.

What is file handling?

File handling is simply using Python to create, read, write, and update files.

For example, I can create a text file called notes.txt and use Python to store information in it.

The function I use is open().

Opening a file

I can open a file like this:

file = open("notes.txt", "r")

The "r" means I'm opening the file for reading.

I can then read the contents:

content = file.read()

print(content)

And when I'm finished:

file.close()

This works, but I quickly learnt that there is a better way.

Using with open()

Instead of manually closing the file, I can use with.

with open("notes.txt", "r") as file:

content = file.read()

print(content)

Python automatically handles closing the file after I'm done.

This is the approach I prefer.

Reading a file

There are a few ways to read a file.

read()

read() gives me the entire file as one string.

For example:

with open("notes.txt", "r") as file:

content = file.read()

print(content)

If the file contains:

I am learning Python.

I get that entire text back.

readline()

readline() reads one line.

For example:

with open("notes.txt", "r") as file:

line = file.readline()

print(line)

This is useful when I only need the first line or want to process a file one line at a time.

readlines()

readlines() reads all the lines and gives them to me as a list.

For example:

with open("notes.txt", "r") as file:

lines = file.readlines()

print(lines)

If the file contains:

Bread

Milk

Sugar

I get something similar to:

["Bread\n", "Milk\n", "Sugar\n"]

I can also loop directly through the file:

with open("notes.txt", "r") as file:

for line in file:

print(line.strip())

I like this approach when working with files containing many records.

Writing to a file

If I want Python to write something into a file, I use "w".

For example:

with open("notes.txt", "w") as file:

file.write("I am learning Python.")

Now the text is saved inside notes.txt.

One thing I had to learn here is that "w" can overwrite what is already in the file.

So if I already had:

I am learning Python.

and then ran:

with open("notes.txt", "w") as file:

file.write("I am learning SQL.")

the old text would be replaced.

Appending to a file

What if I want to keep the old information and add something new?

That's where "a" comes in.

For example:

with open("notes.txt", "a") as file:

file.write("\nI am also learning SQL.")

Now the file contains both pieces of information.

This made sense to me for things like logs, transactions, or contact books where I'm constantly adding new records.

A practical contact book

One of the examples that helped me understand file handling was saving contacts.

I can start with a dictionary:

contacts = {"Amina": "0712345678", "Brian": "0723456789", "Feddy": "0734567890"}

I can save them to a file:

with open("contacts.txt", "w") as file:

for name, phone in contacts.items():

file.write(f"{name}: {phone}\n")

Now my contacts.txt file will contain:

Amina: 0712345678

Brian: 0723456789

Feddy: 0734567890

This was the point where file handling started feeling like something I could actually use.

Adding a new contact

Later, I can add another contact without deleting the existing ones:

name = "Faith"

phone = "0745678901"

with open("contacts.txt", "a") as file:

file.write(f"{name}: {phone}\n")

Now Faith is added to the file.

Reading the contacts back

I can also open the file later and read the saved contacts:

with open("contacts.txt", "r") as file:

for line in file:

print(line.strip())

This is what really made the concept click for me.

My program can save data, close, and later open the file and get the data back.

File modes

The three modes I used most are:

"r" → read

"w" → write

"a" → append

So I started thinking about them like this:

I want to see what's already there → "r"

I want to create or replace the contents → "w"

I want to add something without deleting what's already there → "a"

Checking whether a file exists

Sometimes I don't know whether a file already exists.

Python provides the os module for this.

For example:

import os

if os.path.exists("contacts.txt"):

print("File exists")

else:

print("File does not exist")

This became useful when I started thinking about programs that need to work with files safely.

Working with lines

Suppose I have a file containing product names:

Bread

Milk

Sugar

I can read each one and clean it:

with open("products.txt", "r") as file:

for line in file:

product = line.strip()

print(product)

The strip() removes the newline character and any unnecessary spaces.

This connects nicely with what I learnt about strings.

What I understood

The biggest thing I learnt about file handling is that it gives my Python programs a way to remember information after they stop running.

The basic idea became:

open() → access the file

read() → get information

write() → save or replace information

append() → add information

close() → close the file

And using:

with open(...)

makes the process much cleaner.

Final thoughts

Before learning file handling, my programs only remembered things while they were running.

After learning it, I could save contacts, notes, products, and other information to a file and use that information later.

That was a small but important step for me because Python started feeling less like a language for simple exercises and more like something I could use to build actual programs.

Top comments (0)