Python : A simple to do list

This post is about understanding file i/o in python. This post explains file i/o through a simple to-do list application. The topics covered in this post includes os.path module, file reading, file writing. This post targets basic concept of file i/o hence no exception handling is added.

In real program we might be using a database like sqlite to store items, but for a simple program like this let us create a simple folder called db with a file in it to store the items. We want this db to reside in the same path where our program resides. So let us start creating the db folder .

def get_db_path():
    path = os.path.abspath(os.path.join('.', 'db'))
    if not os.path.exists(path):
    return path

New entires from user is stored in a list.

data = []

def add_entry(item):
    This function adds a new entry to to-do list
    :param item: new to do item
    :return: None
    data.append(item + "\n")

save() opens the file in append mode. (a+) ensures that file get created, if file does not exists.

file_name = 'data.jrl'

def save():
    This function saves the newly added to do items to data base
    :return: None
    db_folder = get_db_path()
    file = os.path.join(db_folder, file_name)
    with open(file,'a+') as fout:
        for item in data:

load() reads the file and returns the entries to the user. We use str.rstrip() to remove new lines and spaces at end of each entries.

def load():
    This function reads the todo list db (file) and returns list of items.
    :return: items in todolist
    items = []
    db_folder = get_db_path()
    file = os.path.join(db_folder, file_name)
    if os.path.exists(file):
        with open(file, 'r') as fin:
            for item in fin.readlines():
    return items

The entire file operation code resides in a separate module ‘’ and now let us see the main program file.

if __name__ == '__main__':
def start_action():
    while True:
        cmd = input("Enter the command : [L]ist, [A]dd, E[X]it : ").lower().strip()
        if cmd == 'l':
            items = journal.load()
        elif cmd == 'a':
            data = input("Enter item : ")
        elif cmd == 'x':
            print("Invalid option{}".format(cmd))
    print('saved and exiting..')

def print_items(items):
    for index, item in enumerate(items):
        print("* {} - {}".format(index,item))

As mentioned above,goal of this post is to share basic file i/o in python and you should add proper exception handling in real code.

             To Do List                 

Enter the command : [L]ist, [A]dd, E[X]it : L
* 0 - Item1
Enter the command : [L]ist, [A]dd, E[X]it : A
Enter item : Item2
Enter the command : [L]ist, [A]dd, E[X]it : L
* 0 - Item1
* 1 - Item2
Enter the command : [L]ist, [A]dd, E[X]it : x
saved and exiting..

Coding is fun enjoy…