I have problem to create a full coding python file handling. I need all data functions in python will be save in txt file. Below is my coding.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = int(input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top
Management (e.g 1/2/3/4): "))
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
serLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%li "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
Actually, this program should have five requirements. First is staffRegistration(), staffLogin(), staffAttendance(), staffLeaveApplication(), approval() but I have done for two requirements only and I get stuck at staffLogin(). I need every function will be save in txt file (I mean the data in function).
In line 32 you try to convert a String into Integer. Besides, in your main function, you have an unresolved variable userLogin.
The other problem is in line 43 (staffLogin function), You want to write a long integer but you pass a string. I have tried to fix your code except for userLogin in main.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top Management (e.g 1/2/3/4): ")
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
userLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%s "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
There are a lot of problems in the staffLogin() function. e.g. the result of the first input()is bound to serLogin, but this should be userLogin.
If that is corrected, a password is read from the user, but nothing is ever done with it. Should the password be treated as an integer?
Also, if the user enters 2 at first prompt, the code will not set username but it will still try to write username to the file. That will raise a NameError exception.
Finally, the code attempts to write the characters in userLogin to the file as though they are integers. Not only will that not work, it doesn't make sense. Perhaps this should be writing the password to the file?
Related
I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...
I'm just starting with python and I want to make a simple login system with text files. Everytime I run the code I get this error. It doesn't even make the text file. Before this, I could run my code and it made a file but now it doesn't. I tried just one line of code to open a text file but that doesn't work either.(line of code: f = open("demofile.txt")) I also tried to google it, no solution. I don't know what to do?
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
f = open("dataBank.txt", 'w')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if name in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
i dont know whats your logic but to create a file you need to use a w+
try it by de the code
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
try:
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
except:
return 'Data base donest exists. creating one...'
f = open("dataBank.txt", 'w+')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if username in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
The error you get in f = open('demofile.txt') is because open takes an additional argument 'mode' whose default value is 'r' for read. If the passed filename does not exist you get the described error.
Use f = open('demofile.txt','w') instead for writing to a file. This creates a new file if the filename does not exist.
i want to save keys and values in dictionary and use it tomorrow or next week
i have read book "A byte of Python" I want to do questions from book, but i don't understand how work pcikle with dictionaryes
import os
import pickle
addressbook = {}
home = os.environ['HOME']
path = home + '/.local/share/addressbook'
addressbookfile = path + '/' + 'addressbook.data'
if not os.path.exists(path):
os.mkdir(path)
while True:
print("What to do?: ")
print("1 - full list")
print("2 - add a contact")
print("3 - remove contact")
answer = int(input("Number of answer: "))
if answer == 1:
f = open(addressbookfile, 'rb')
storedlist = pickle.load(f)
print(storedlist)
elif answer == 2:
namecontact = str(input("Enter the name of cantact: "))
name = str(input("Enter the name: "))
lastname = str(input("Enter the lastname: "))
number = int(input("Enter the number: "))
addressbook[namecontact] = [name, lastname, number]
f = open(addressbookfile, 'wb')
pickle.dump(addressbookfile, f)
f.close()
Python pickle serialises and deserialises objects and can be used to save variables to file for later use.
As you do, the variables are saved with
pickle.dump(addressbook , f)
You can the load the data with
addressbook = pickle.load(f)
Where f is your file handle
#!/usr/bin/env python3
import csv
# a file in the current directory
FILENAME = "contacts.csv"
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
def list_contacts(contacts):
for i in range (len(contacts)):
contact= contacts[i]
print(str(i+1) +"."+ contact[0])
print()
def view_contact(contacts):
pos = int(input("Number: "))
if not (pos-1)in range(len(contacts)):
print(str(pos) + ' not in list, try again')
view(contacts)
return
contact = []
print(name + email + phone+".\n")
print()
def delete_contact(contacts):
index = int(input("Number: "))
contact = contacts.pop(index -1)
write_contacts(contacts)
print(contact[0]+" was deleted.\n")
def add_contact(contacts):
name=input("Name: ")
email=input("Email: ")
phone=input("Phone number: ")
contact= []
contact.append(name)
contact.append(email)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
def display_menu():
print("Contact Manager")
print()
print("COMMAND MENU")
print("list - List all contacts")
print("view - View a contact")
print("add - Add a contact")
print("delete- Delete a contact")
print()
print()
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower() == "list":
list_contacts(contacts)
elif command.lower()== "view":
view_contact(contacts)
elif command.lower()== "add":
add_contact(contacts)
elif command.lower()== "delete":
delete_contact(contacts)
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")
if __name__ == "__main__":
main()
This all my code. I'm trying to figure out how to make the delete and view commands display an error message when the user enters a number that is invalid but it's not working. I'm also trying to view a contact when the user selects a specific number form list which would then display the email name and phone number of that selected number. I'm currently stuck
The errors im getting are
raceback (most recent call last):
, line 93, in
main()
, line 81, in main
view_contact(contacts)
, line 32, in view_contact
view(contacts)
NameError: name 'view' is not defined
I don't think you has a good start with list into cvs using append, anyway is your example.
You can use remove to remove your contact from list, see examples with list: http://www.thegeekstuff.com/2013/06/python-list
when the user select a specific number from list , just read by stepping to the number phone because you add with: name + email + phone.
adding an error message , use: try except finally
I cannot get my file to store multiple instances of contacts. After adding new contact and trying to print them, it comes up with "IndexError: list index out of range" error. What shall I do to make it work?
import pickle
class People():
def __init__(self, name, surname, age, mobile_no, home_no):
self.name = name
self.surname = surname
self.age = age
self.mobile_no = mobile_no
self.home_no = home_no
def DisplayContacts(self):
print("First Name: \t", self.name)
print("Surname: \t", self.surname)
print("Age: \t", self.age)
print("Mobile Number: \t", self.mobile_no)
print("Home Number: \t", self.home_no)
print()
def addContact():
newname = str(input("First name: \t"))
newsurname = str(input("Surname: \t"))
newage = int(input("Age: \t"))
newmobile_no = int(input("Mobile Number: \t"))
newhome_no = int(input("Home Number: \t"))
newContact = People(newname, newsurname, newage, newmobile_no, newhome_no)
return newContact
cont = 1
contacts = []
while cont == 1:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
contacts.append(addContact())
file = open("CList.pickle", "ab")
pickle.dump(contacts, file, pickle.HIGHEST_PROTOCOL)
file.close()
else:
print ("111")
cont = 0
useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":
with open ("CList.pickle", "rb") as pickled_file:
contacts = pickle.load(pickled_file)
print(contacts[0].surname)
print(contacts[1].surname)
else:
print("Null")
Simply appending a picked object to a file is not the same thing as pickling a list. EAch time you append, you've created another pickled record. Read the file multiple times to get your list:
with open ("CList.pickle", "rb") as pickled_file:
contacts = []
try:
while True:
contacts.append(pickle.load(pickled_file))
except EOFError:
pass
Now, instead of appending the list of contacts (which would give you a list of lists with many duplicates), just pickle the new contact:
with open("CList.pickle", "ab") as _file:
while True:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
pickle.dump(addContact(), _file, pickle.HIGHEST_PROTOCOL)
else:
print ("111")
break