Now let’s write a new program that greets a user whose name has
already been stored:
greet_user.py from pathlib import Path
import json
1 path = Path('[Link]')
contents = path.read_text()
2 username = [Link](contents)
print(f"Welcome back, {username}!")
We read the contents of the data file 1 and then use [Link]() to
assign the recovered data to the variable username 2. Since we’ve recovered
the username, we can welcome the user back with a personalized greeting:
Welcome back, Eric!
We need to combine these two programs into one file. When someone
runs remember_me.py, we want to retrieve their username from memory if
possible; if not, we’ll prompt for a username and store it in [Link] for
next time. We could write a try- except block here to respond appropriately
if [Link] doesn’t exist, but instead we’ll use a handy method from the
pathlib module:
remember from pathlib import Path
_me.py import json
path = Path('[Link]')
1 if [Link]():
contents = path.read_text()
username = [Link](contents)
print(f"Welcome back, {username}!")
2 else:
username = input("What is your name? ")
contents = [Link](username)
path.write_text(contents)
print(f"We'll remember you when you come back, {username}!")
There are many helpful methods you can use with Path objects. The
exists() method returns True if a file or folder exists and False if it doesn’t.
Here we use [Link]() to find out if a username has already been stored 1.
If [Link] exists, we load the username and print a personalized greeting
to the user.
If the file [Link] doesn’t exist 2, we prompt for a username and
store the value that the user enters. We also print the familiar message that
we’ll remember them when they come back.
Whichever block executes, the result is a username and an appropriate
greeting. If this is the first time the program runs, this is the output:
What is your name? Eric
We'll remember you when you come back, Eric!
Files and Exceptions 203