Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
checking username
#1
Hi, I'm reading Python Crashcourse (third edition), chapter 10 (about files).
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 None
My (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()
buran write Jun-17-2024, 05:46 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Usually there are more than one user in a username file. You would do a comparison for said username.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
(Jun-17-2024, 05:34 AM)menator01 Wrote: Usually there are more than one user in a username file. You would do a comparison for said username.

Yes, but how do i know the correct username?
Reply
#4
They should have written usernames, that would be less confusing for you perhaps.

Try like this maybe? Make your own file, then save it and then open it.

Of course, you need to set your own path, don't try to use my path!

import json
from pathlib import Path

path2json = '/home/pedro/temp/usernames.json'
mypath = Path(path2json)
data = []
username = 'X'
# enter usernames and emails
while not username == 'q':
    users_dict = {}
    username = input(f'Enter your username, enter q to quit ... ')
    if username == 'q':
            break
    email = input('enter your email ... ')
    users_dict['user name'] = username
    users_dict['user email'] = email
    data.append(users_dict)

# save the data
with open(mypath, 'w', encoding='utf-8') as fp:
    json.dump(data, fp, ensure_ascii=False, indent=4)

# open the data to inspect it
with open(mypath) as fp:
    data_list = json.load(fp)

# find Tarzan
for d in data_list:
    if d['user name'] == 'Tarzan':
        print(d)
        print(d['user name'])

Output:
{'user name': 'Tarzan', 'user email': '[email protected]'} Tarzan
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  AttributeError: '_tkinter.tkapp' object has no attribute 'username' Konstantin23 4 2,293 Aug-04-2023, 12:41 PM
Last Post: Konstantin23
  Hiding username and password on sql tantony 10 3,397 Oct-21-2022, 07:58 PM
Last Post: wavic
  Pulling username from Tuple pajd 21 4,136 Oct-07-2022, 01:33 PM
Last Post: pajd
  Trying to create a conditional with a username Realen 2 1,942 Jun-20-2020, 12:44 AM
Last Post: Realen
  Client OS username ImPyBoy17 5 2,851 Sep-24-2019, 10:18 AM
Last Post: buran
  creating a username and pword program using a #def statement and #dictionary zcode12 3 3,301 Oct-14-2018, 04:41 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020