filename ='programming.txt'withopen(filename,'a')as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
defcount_words(filename):"""Count the approximate number of words in a file."""try:withopen(filename, encoding='utf-8')as f_obj:
contents = f_obj.read()except FileNotFoundError:passelse:# Count approximate number of words in the file.
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+" words.")
filenames =['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']for filename in filenames:
count_words(filename)
import json
defget_stored_username():"""Get stored username if available."""
filename ='username.json'try:withopen(filename)as f_obj:
username = json.load(f_obj)except FileNotFoundError:returnNoneelse:return username
defget_new_username():"""Prompt for a new username."""
username =input("What is your name? ")
filename ='username.json'withopen(filename,'w')as f_obj:
json.dump(username, f_obj)return username
defgreet_user():"""Greet the user by name."""
username = get_stored_username()if username:print("Welcome back, "+ username +"!")else:
username = get_new_username()print("We'll remember you when you come back, "+ username +"!")
greet_user()