Tutorial for first year computer science students

Back to Tutorials

User Login 2 - File Operations

Learning Objectives

We are going to learn:

  1. How to open, read and write to files in Python.

Exercises

Download the Medialib ex10 login.txt file and 5 image files (as shown below) from the gallery and modify your program from exercise 9 to allow for user account creation.

MediaLib Dice Exercise

Write a function to read the login.txt file using open("login.txt", "r", encoding="utf-8").readlines(). Parse each line and store the username and password into a dictionary

With a dictionary that have usernames as keys and passwords as values, which is like login_dict={“taro”: “1234”, “hanako”: ”asdf”, ...}, create a user login program that loops the following processes until the user successfully logged in.

  1. If the username does not exist, then print “No such user!”, and display “wrong_user.png”, then use input() function with a prompt “Do you want to create a new account for the user (yes/no): ” to get the user’s input.
  2. If the user inputs "yes", then display “password.png” and use input() function with a prompt “Password: ” to get the new password. And then, save the new username and password to the file “login.txt” and print “New user created!”. At the end, display “welcome.png”, and finish the program.
MediaLib Exercise




Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.