I am trying to make a contacts python project but I don't know how to fin da single user. I have tried to find from the file but I am not able to, kindly give the code for that part. If you find any other mistakes kindly resolve that too
This is the code.
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 17:56:45 2020
#author: Teerth Jain
"""
import time
from transpositionDecrypt import decryptMessage as dm
from transpositionEncrypt import encryptMessage as em
key = 8
users = {}
users1 = {}
print("Welcome to Teerth's Contacts Saver and Reader...")
time.sleep(0.5)
r_or_w = input("Do you want or (r)ead or (a)dd or (d)el contacts: ")
if r_or_w == 'r':
what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
#here is the part where you need to give me advice#
if what == 'n':
print("Displaying the whole list...")
q = open('contacts.txt', 'r')
for liness in q:
print(dm(key, liness.strip()))
if r_or_w == 'a':
while True:
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
file2 = open('contacts.txt', 'r')
y = dm(key, file2.read())
if addwho in y:
print("User in contact list, please try again")
addwho = input("Please enter the name: ")
number = input("Please enter the number: ")
users1.update(addwho = number)
file1 = open('contacts.txt', 'a')
q = f'{addwho} : {number}'
file1.write(em(key, q))
file1.write("\n")
file1.close()
print("Number is ciphered and added.")
again = input("Do you want to add another contact(y, n): ")
if again == 'n':
break
There are no such errors now but if you can modify the code to make it better, kindly do it
Thanks
Related
Im able too generate a number properly how I want but I want too make a custom input so the user can generate an exact amount of numbers not just a set amount of numbers.
if menu == "1":
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
To do this, you can use a while True loop that takes in input every single time they want to input a phone number. If they input something that you don't want, break out of the while True loop. Otherwise, you take in the phone number. To hold the set of numbers, just add them to arrays.
Edited off your code:
if menu == "1":
while(True):
code = input("")
if code == "":
countrycode = input("Please Enter Country Code: ")
areacode = input("Enter area Code: ")
city = (random.randint(200,999))
last = (random.randint(1000,9999))
number = ("+"+countrycode+areacode+str(city)+str(last))
print(number)
else:
break
I'm not sure I fully understand your question, but i'll give it a shot:
import random
class Data():
def __init__(self) -> None:
country_code = ""
area_code = ""
city = ""
last = ""
def __str__(self):
return f"+{self.country_code}-{self.area_code}-{self.city}-{self.last}"
def main():
number_of_entries = int(input("How Many Entries: "))
list_of_information = []
for _ in range(0, number_of_entries):
new_data = Data()
new_data.country_code = input("Please Enter Country Code: ")
new_data.area_code = input("Enter area Code: ")
new_data.city = str(random.randint(200,999))
new_data.last = str(random.randint(1000,9999))
list_of_information.append(new_data)
for entry in list_of_information:
print(entry)
if __name__ == '__main__':
main()
Sample:
How Many Entries: 2
Please Enter Country Code: 1
Enter area Code: 604
Please Enter Country Code: 1
Enter area Code: 30
+1-604-394-5276
+1-30-840-8783
I have a text file named universitylist.txt. When the user's input matches the college name, the college and city are returned. I am trying to add an IF statement that will return a random entry from the file when the user enters "random college". I am searching for the best way to do this. I tried appending random.LineItem in the print statement but that doesn't work.
e#!/usr/bin/env python3
from random import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
**if user_input == "random college":
rando_entry = random.schoollist_dict(lineitem)
print(rando_entry)**
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__": main() # Main entry point for the applications
nter code here
Add this to your code,
import random #goes on top
random.choice(list(schoollist_dict.values()))
So something like this,
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
Make sure you import random on top.
I created a textfile with 2 columns and the code above works for me when I updated your code with it.
Your final code should look like this,
import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__":
main() # Main entry point for the applications
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
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?
This is my code for entering student details. Once the user has entered the details and inputs yes, the details are exported to StudentDetails.csv (Microsoft Excel) where it should go below the headers but ends up going somewhere else.
def EnterStudent():
uchoice_loop = False
ask_loop = False
while uchoice_loop == False:
surname = raw_input("What is the surname?")
forename = raw_input("What is the forname?")
date = raw_input("What is the date of birth? {Put it in the format D/M/Y}")
home_address = raw_input("What is the home address?")
home_phone = raw_input("What is the home phone?")
gender = raw_input("What is their gender?")
tutor_group = raw_input("What is their tutor group?")
email = (forename.lower() + surname.lower() + ("#school.com"))
print(surname+" "+forename+" "+date+" "+home_address+" "+home_phone+" "+gender+" "+tutor_group+" "+email)
ask = raw_input("Are these details correct?"+"\n"+"Press b to go back, or yes to add entered data on your student.").lower()
if ask == "yes":
f = open("StudentDetails.csv","rt")
lines = f.readlines()
f.close()
lines.append(surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email+"\n")
f = open("StudentDetails.csv", "w")
f.writelines(lines)
f.close()
uchoice_loop = True
printMenu()
elif ask == "b":
uchoice_loop = False
else:
print("Plesase enter 'b' to go back or 'yes' to continue")
This is my csv file.
enter image description here
There's a few things you can do to make this work. You dont need to open the StudentDetails.csv and read all of the lines. Instead you can make a lines string variable and append it the the StudentDetails.csv like in the example below
#f = open("StudentDetails.csv","rt")
#lines = f.readlines()
#f.close()
lines = surname+","+forename+","+date+","+home_address+","+home_phone+","+gender+","+tutor_group+","+email
# the "a" appends the lines variable to the csv file instead of writing over it like the "w" does
f = open("StudentDetails.csv", "a")
f.writelines(lines)
f.close()
uchoice_loop = True
Eric is right in that you best open the file in append-mode (see https://docs.python.org/3.6/library/functions.html#open) instead of cumbersomely reading and rewriting your file over and over again.
I want to add to this that you probably will enjoy using the standard library's csv module as well (see https://docs.python.org/3.6/library/csv.html), especially if you want to use your output file in Excel afterwards.
Then, I'd also advise you to not use variables for while loop conditionals, but learning about the continue and break statements. If you want to break out of the outer loop in the example, research try, except and raise.
Finally, unless you really have to use Python 2.x, I recommend you to start using Python 3. The code below is written in Python 3 and will not work in Python 2.
#!/usr/bin/env python
# -*- codig: utf-8 -*-
import csv
def enterStudent():
b_or_yes = 'Press b to go back, or yes to save the entered data: '
while True:
surname = input('What is the surname? ')
forename = input('What is the first name? ')
date = input(
'What is the date of birth? {Put it in the format D/M/Y} ')
home_address = input('What is the home address? ')
home_phone = input('What is the home phone? ')
gender = input('What is the gender? ')
tutor_group = input('What is the tutor group? ')
email = forename.lower() + surname.lower() + '#school.com'
studentdata = (
surname,
forename,
date,
home_address,
home_phone,
gender,
tutor_group,
email)
print(studentdata)
while True:
reply = input('Are these details correct?\n' + b_or_yes).lower()
if reply == 'yes':
with open('studentdetails.csv', 'a', newline='') as csvfile:
studentwriter = csv.writer(csvfile, dialect='excel')
studentwriter.writerow(studentdata)
break
elif reply == 'b':
break
if __name__ == '__main__':
enterStudent()
Best of luck!