Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Using Databases in Python Gettin' CRUD-y With It Add An Entry

Laurens Sandt
Laurens Sandt
3,513 Points

EOFerror file while using control D

I run into an EOFerror with tghis code. I caught it with two Try-Except blocks. That however creates an infinite loop. I have researched a bit further so control Z seems to be the proper solution instead of control D. But this also hardly satisfactory because it provides a strange transation to: if input("Save entry Y/n: ").lower() != 'n':

it actually gives you the control Z and you have to enter it to make the transition. Using control z seems an inferior solution.

db = SqliteDatabase('diary.db')

class Entry(Model): content = TextField() timestamp = DateTimeField(default=datetime.datetime.now) # not adding () after now ensures the function is called everytime an antry is made # as supposed to just when running the script

class Meta:
    database = db

def initialize(): '''create database and table if they don't exist''' db.connect() db.create_tables([Entry], safe=True)

def menu_loop(): '''show menu''' choice = None

while choice != 'q':
    print("Enter 'q' to quit")
    for key, value in menu.items():
        print("{}) {}".format(key, value.__doc__))
    try:
        choice = input("Action: ").lower()
    except EOFError:
        continue
    if choice in menu:
        menu[choice]()

def add_entry(): """add entry in the diary""" print("Add your entry. Press ctrl+d when finished") data = sys.stdin.read().strip()

if data:
    try:
        if input("Save entry Y/n: ").lower() != 'n':
            Entry.create(content=data)
            print("Saved succesfully!")
    except EOFError:
        print("Save aborted")

def view_entries(): '''show the entries existing in the diary'''

def delete_entry(): '''Delete an existing entry in the diary'''

menu = OrderedDict([ ('a', add_entry), ('v', view_entries) ])

if name == 'main': initialize() menu_loop()