๐ Beginning Python Programming
/
Files Operation
/
Code Example: Diary Text File
Diary v2
import os.path
import datetime
def today():
return str(datetime.date.today())
def diary_file_path():
script_dir = os.path.dirname(__file__)
return os.path.join(script_dir, 'diary.txt')
def ask_for_input():
content = input("What do you want to say to Mr. Diary? ")
if len(content) > 0:
write_file(today() + ": " + content)
def write_file(content):
with open(diary_file_path(), "a") as file_obj:
file_obj.write(content + "\n")
def read_last_entries():
with open(diary_file_path(), "r") as file_obj:
lines = file_obj.readlines()
print("".join(lines[-3:]).rstrip())
ask_for_input()
read_last_entries()