import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
#classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
I am trying to make some sort of simplified python, but hitting errors only on the CheckDetails() function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help?
You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
Related
I am currently building a school homework project - a contact manager, using classes in Python.
I was able to assemble all the needed parts to make my code work, yet upon exiting the program with Terminal, the data inside of my JSON file keep being overwritten.
I've tried changing the with open attribute to "w" and "a", sadly nothing works.
Main Code:
from colorama import Fore, Style
from LoadAndSave import load_file, save_file
from ContactBook import ContactBook
contacts = []
DATA_FILE = "contactbook.json"
def menu():
print(Fore.RED + "Welcome to Contacts Manager v2.0.0!" + Style.RESET_ALL)
print(Fore.LIGHTCYAN_EX + "Please enter your selection according to the menu." + Style.RESET_ALL)
print("a - Add a contact")
print("r - Remove a contact")
print("s - Search for a contact")
print("p - Print a list of all contacts")
print("x - Exit")
user_selection = input(Fore.GREEN + "Your selection: " + Style.RESET_ALL)
return user_selection
def main():
load_file(DATA_FILE)
contactbook = ContactBook()
user_selection = ""
while user_selection != "x":
user_selection = menu() # As long as user did not select "x", program will always run.
if user_selection == "a":
contactbook.add_contact(input("Please enter contact's name: "), int(input("Please enter contact's number: ")))
if user_selection == "r":
contactbook.remove_contact(contactbook.search_contact(input("Contact's Name? ")))
if user_selection == "s":
contactbook.search_contact(input("Contact's name?"))
print(Fore.GREEN + "Success!" + Style.RESET_ALL)
if user_selection == "p":
print(contactbook)
print(Fore.GREEN + "Success!" + Style.RESET_ALL)
print(Fore.MAGENTA + "Thank you for using my software. Bye!")
save_file(contactbook.make_contact_json(), DATA_FILE)
if __name__ == "__main__":
main()
Load and save:
import json
def load_file(DATA_FILE): # Loading JSON file with all information
with open (DATA_FILE) as file:
return json.load(file)
def save_file(json_list, DATA_FILE):
with open (DATA_FILE, "w") as file:
json.dump(json_list, file, indent = 4)
Contact & ContactBook classes:
import json
class Contact:
name = ""
tel = 0
def __init__(self, name = "", tel = 0):
self.name = name
self.tel = tel
def __str__(self):
return json.dumps({"contact_info":[{"name": self.name, "tel": self.tel}]})
from colorama import Fore, Style, Back
from Contact import Contact
import json
class ContactBook:
contacts = []
def __init__(self):
pass
def add_contact(self, name = "", tel = 0):
self.contacts.append(Contact(name, tel))
print(Fore.GREEN + "Success!" + Style.RESET_ALL)
def remove_contact(self, contact_name):
self.contacts.remove(contact_name)
print(Fore.RED + "Removed.\n" + Style.RESET_ALL)
def search_contact(self, contact_name):
for contact in self.contacts:
if type(contact) is Contact:
if contact.name == contact_name:
return contact
return (Back.RED + "\nThere is no contact with that name." + Style.RESET_ALL + "\n")
def make_contact_json(self):
result = []
for contact in self.contacts:
result.append(json.loads(contact.__str__()))
return result
def __str__(self) -> str:
result = ""
for contact in self.contacts:
result += contact.__str__()
return result
JSON File:
[
[
{
"name": "sdfgh",
"tel": 654321
}
]
]
Thanks in advance to all helpers!
Your contacts are getting overwritten because every time you run your program, you are creating a fresh ContactBook
contactbook = ContactBook() # In your Main Code
This in turn initializes an empty contacts list
contacts = [] # Inside Class ContactBook
I suggest that you add an __init__ logic to you ContactBook Class that initialises your contacts list with the existing ones
Something Like
class ContactBook:
def __init__(self, existing_contacts=None):
self.contacts = [] if existing_contacts is None else existing_contacts
Also while creating the ContactBook object in you main code please pass the existing contacts.
try:
existing_contacts = load_file(DATA_FILE)
except FileNotFoundError:
existing_contacts = None
contactbook = ContactBook(existing_contacts)
Also please make sure that you are saving the contacts correctly. It seems to currently be a list of list of objects where as it should ideally be a list of objects
Hope you get good grades. Peace out.
Basically im doing a project in python as part of my full stack course, and i have ran into wall.
My project is a parking lot system, which gets you a ticket with your cars number, unique code, time entered. At the exit you will have to write the unique code and it will calculate the cost for the parked time. I created a class named Key which creates the object it self with the exit time as None, but my trouble begins by trying to update the self.exit which doesn't work out for me using the the function exit_time. Every time a car enters the data is written to a file using pickle, i tried using a list to be able to edit the object but something isn't working out for me.
Also I tried many varieties by calling the function or what happens in the function it self.
THIS IS MY MAIN
list_of_cars = []
while True:
startmessage() # prints message
choice() # prints message
action = input("\nYour choice: ")
if action == "1":
choice_one() # prints message
car_number = input(" here: ")
new_client = Key(car_number)
list_of_cars.append(new_client)
writing_file(list_of_cars)
reading_file()
if action == "2":
choice_two() # prints message
exit_key = input(" here: ")
Key(exit_key).exit_time(exit_key)
READ AND WRITE
def reading_file():
with open("parking.data", "rb") as readfile:
list_of_cars = pickle.load(readfile)
print("testing", [str(x) for x in list_of_cars])
readfile.close()
return list_of_cars
def writing_file(list_of_cars):
with open("parking.data", "wb") as myfile:
pickle.dump(list_of_cars, myfile)
myfile.close()
return list_of_cars
THE CLASS
import random
import pickle
import datetime as dt
class Key:
def __init__(self, car_number):
self.car_number = car_number
self.key = self.generate()
self.enter = self.enter_time()
self.exit = None
"""
creates the key it self and while creating it checks if it already exists so that there will be no duplicates
"""
def generate(self):
key = ""
chunk = ""
alphabet = "ABCDEFGHIJKLMNOPQRZTUVWXYZ1234567890"
while True:
while len(key) < 8:
char = random.choice(alphabet)
key += char
chunk += char
if len(chunk) == 3:
key += "-"
chunk = ""
key = key[:-1]
with open("parking.data", "rb") as readfile:
new_list = pickle.load(readfile)
if key in new_list:
key = ""
else:
return key
def __str__(self):
return f"{self.car_number},{self.key}," \
f"{self.enter},{self.exit}"
def enter_time(self):
start = str(dt.datetime.now().strftime('%H:%M:%S'))
return start
def exit_time(self, exit_key):
from read_and_write import reading_file
list_of_cars = reading_file()
if exit_key in list_of_cars:
self.exit = str(dt.datetime.now().strftime('%H:%M:%S'))
print("IT WORKED!!!")
print("got to the function :/")
your conditional is:
if exit_key in list_of_cars:
exit_key is OM7-XVX
list_of_cars is ['5412,OM7-XVX,21:09:42,None1',...]
So...
'OM7-XVX' in ['5412,OM7-XVX,21:09:42,None1'] -> False
'OM7-XVX' in ['5412,OM7-XVX,21:09:42,None1'][0] -> True
Therefore replace the conditional with
if any(exit_key in v for v in list_of_cars):
I am fairly new to Python and am trying this project. I need to store usernames and passwords in a text file ( to create a database). I have used the pickle module. The code I've tried erases previously-stored data every time I run the code.
I have understood that I have to append data to the file instead of writing to it but I don't know how. How can I correct the code?
import pickle
# pickle mod converts obj into byte stream to store in database
import time
def load_Dictionary():
try :
with open("UserDict.txt" , "rb") as ufile :
return pickle.load(ufile)
except IOError :
with open("UserDict.txt" , "ab") as ufile :
pickle.dump(dict() , ufile)
return dict()
def save_Dictionary(UserDict):
with open("UserText.txt" , "wb") as ufile :
pickle.dump(UserDict , ufile)
def new_User_Login():
userDict = load_Dictionary() # dictionary is loaded
checkUserAcc = input("Are you a new user ( Yes or No ) ? ")
# insert buttons for yes no
# tk.Button(window, text="", command=password_generator).pack(pady=10)
if (checkUserAcc == "Yes" or checkUserAcc == "yes" or checkUserAcc == "YES"):
username = input("Please enter your username : ")
Root_password = input ("Please enter your password :")
if ( username in userDict):
print("Username you entered is not available")
new_User_Login()
else :
userDict[username] = Root_password
print("Login Successful!")
save_Dictionary(userDict) # saves new login info
time.sleep(2.0)
elif (checkUserAcc == "No" or checkUserAcc == "no" or checkUserAcc == "NO") :
user_login()
else :
print("Invalid input! Try Again.")
new_User_Login()
def user_login():
global username
global Root_password
global tries
login_Username = input("Enter your Username : ")
login_Password = input("Enter your Password : ")
UserDict = load_Dictionary()
if ( tries < 5):
for key in UserDict:
if (login_Username == key and login_Password == UserDict[key]):
print("You have successfully logged in !")
else :
print("Login Failed! Please try again")
tries = tries + 1
user_login()
if( tries >= 5 ):
print("You have attempted login too man times. Try again later. ")
time.sleep(30.0)
tries = 1 # reset tries counter
user_login()
global tries
tries=1
new_User_Login()
It appears you were using "wb" instead of "ab" in this function, which caused the file to reset everytime you wished to save to it. Also, The filename should be "UserDict", instead of "UserText".
def save_Dictionary(UserDict):
with open("UserDict.txt" , "ab") as ufile:
pickle.dump(UserDict , ufile)
I am new to python and having some trouble outputting my data into a csv file. the script runs but the file is blank that is created with no data.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
You may just have some extra indentation. Here's the same script but some indentation has been removed on lines 19 and 20.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
There's an else missing. Your input is not appending anything to shop_list and thus nothing gets written to the file.
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
else: # <<< missing
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
I am currently attempting to make a login/signup program on my computer that will allow for multiple sets of usernames and passwords. Right now anytime I sign up, it overwrites the previous login. I am using Python 3.4.
Is there a way I can prevent this?
My code is available below:
import os
import pickle
import sys
import time
user_name = 'default'
pass_word = '12345'
login = {'username' : user_name,
'password' : pass_word}
def cls():
os.system('cls')
def space():
print(' ')
def load():
with open('logins', 'rb') as f:
login = pickle.load(f)
def save():
with open('logins', 'wb') as f:
pickle.dump(login, f)
def MainMenu():
print('Select an Option.')
while True:
print('1) Login')
print('2) Signup')
user_input = input('Option #: ')
if user_input == '1':
cls()
login_user()
elif user_input == '2':
cls()
signup_user()
else:
cls()
continue
def signup_user():
user_chosen_name = input('Username: ')
login['username'] = user_chosen_name
user_chosen_password = input('Password: ')
login['password'] = user_chosen_password
space()
cls()
print('Setup complete. Please login.')
os.system('pause')
save()
cls()
login_user()
def login_user():
load()
while True:
print('Please Login.')
space()
user_input_name = input('Username: ')
user_input_password = input('Password: ')
if user_input_name == login['username'] and user_input_password == login['password']:
space()
print('Login Successful.')
else:
space()
print('Login Failed. Please Try Again.')
while True:
print('1) Try Again.')
print('2) Main Menu.')
user_cont = input('Continue?: ')
if user_cont == '1':
cls()
break
elif user_cont == '2':
cls()
MainMenu()
break
if __name__ == '__main__':
if os.path.isfile('logins') == False:
save()
else:
pass
MainMenu()
Here are two proposals for the login/password data model.
Use a dictionary, this is probably the simplest way ; I suggest using this.
# init with default
passwords = {user_name: pass_word}
# password look-up
if login in passwords:
print passwords[login]
else:
print 'User', login, 'is not registered'
# password set or update
password[login] = new_password
List of couples or list of dictionaries.
This may be closer to your current solution, but I would not recommend it.
I only show what the initialization would be.
# list of couples
logins = [(user_name, pass_word)]
# list of dictionaries
logins = [{'username' : user_name,
'password' : pass_word}]