Last active
January 11, 2019 22:27
-
-
Save AO8/f7f3dd87056db8a90317cdeac802b957 to your computer and use it in GitHub Desktop.
More File I/O practice: a simple MyJournal app with Python 3, taken from Michael Kennedy's Python Jumpstart by Building 10 Apps course.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def load(name): | |
""" | |
This method creates and loads a new journal. | |
:param name: This base name of the journal to load. | |
:return: A new journal data structure populated with file data. | |
""" | |
data = [] | |
filename = get_full_pathname(name) | |
if os.path.exists(filename): | |
with open(filename, "r") as fin: | |
for entry in fin.readlines(): | |
data.append(entry.rstrip()) | |
return data | |
def save(name, journal_data): | |
filename = get_full_pathname(name) | |
print("...saving to: {}".format(filename)) | |
with open(filename, "w") as fout: | |
for entry in journal_data: | |
fout.write(entry + "\n") | |
def get_full_pathname(name): | |
filename = os.path.abspath(os.path.join(".", "journals", name + ".jrl")) | |
return filename | |
def add_entry(text, journal_data): | |
journal_data.append(text) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Project adapted from Michael Kennedy's Python Jumpstart by Building 10 Apps course | |
import journal | |
def main(): | |
print_header() | |
run_event_loop() | |
def print_header(): | |
print("-----------------------------") | |
print(" JOURNAL APP ") | |
print("-----------------------------") | |
print() | |
def run_event_loop(): | |
print("What would you like to do?") | |
cmd = "EMPTY" | |
journal_name = "default" | |
journal_data = journal.load(journal_name) | |
while cmd != "X" and cmd: | |
cmd = input("[L]ist entries, [A]dd an entry, e[X]it: ") | |
cmd = cmd.upper().strip() | |
if cmd == "L": | |
list_entries(journal_data) | |
elif cmd == "A": | |
add_entry(journal_data) | |
elif cmd != "X" and cmd: | |
print("Sorry, I don't understand '{}'. Please try again.".format(cmd)) | |
print("Saving journal...)") | |
print("Done, goodbye!") | |
journal.save(journal_name, journal_data) | |
def list_entries(data): | |
print("Your journal entries:") | |
entries = reversed(data) | |
for idx, entry in enumerate(entries): | |
print("* [{}] {}".format(idx + 1, entry)) | |
def add_entry(data): | |
text = input("Type your entry, <enter> to exit: ") | |
journal.add_entry(text, data) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment