Jun-17-2024, 05:10 AM
(This post was last modified: Jun-17-2024, 09:08 PM by Larz60+.
Edit Reason: fixed code tags (as stated by buran)
)
Hi, I'm reading Python Crashcourse (third edition), chapter 10 (about files).
The code is:
Complete code:
The code is:
from pathlib import Path import json def get_stored_username(path): if path.exists(): contents = path.read_text() username = json.loads(contents) return username else: return NoneMy (logical?) question is how does the code knows the username. In other words the code checks for the existence of a username.json but how does the code knows this file belongs to the user running the code?
Complete code:
from pathlib import Path import json def get_stored_username(path): """Get stored username if available.""" if path.exists(): contents = path.read_text() username = json.loads(contents) return username else: return None def get_new_username(path): """Prompt for a new username.""" username = input("What is your name? ") contents = json.dumps(username) path.write_text(contents) return username def greet_user(): """Greet the user by name.""" path = Path('username.json') username = get_stored_username(path) if username: print(f"Welcome back, {username}!") else: username = get_new_username(path) print(f"We'll remember you when you come back, {username}!") greet_user()