I am quite new to python and I am getting an attribute error.
import FileHandeling as fh;
import os;
CounterFilePath = os.path.dirname(os.path.realpath(__file__))+"/counter.txt";
FilePath = os.path.dirname(os.path.realpath(__file__))+"/FileIO.txt";
class Employee:
def createEmployee(self):
numOfEmployees = int(input("Enter number of employees: "));
empDetails = [];
for i in range(numOfEmployees):
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = str(i)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
empDetails.append(string);
with open(FilePath,"a+") as fo:
fo.seek(0);
fh.createFile(fo,numOfEmployees,empDetails,CounterFilePath);
def searchEmployee(self):
choice = int(input("Press:\n1 to search by First Name\n2 to search by Last Name\n3 to search by Salary\n4 to search by Email ID\n"));
print "Enter the",;
if(choice == 1):
print "First Name:",;
elif(choice == 2):
print "Last Name:",;
elif(choice == 3):
print "Salary:",;
elif(choice == 4):
print "Email ID:",;
searchStr = raw_input();
with open(FilePath,"r") as fo:
string = fh.readFile(fo,searchStr,choice-1);
while line in string:
print line;
def updateEmployee(self):
print "Leave the entries empty if you dont want to update that entry.";
lineNum = input("Enter the line number of the entry you want to update: ");
with open(FilePath,"r") as fo:
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
if(empFName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empFName = empDetails[1];
if(empLName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empLName = empDetails[2];
if(empSalary == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empSalary = empDetails[3];
if(empEmailId == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empEmailId = empDetails[4];
updateStr = str(lineNum-1)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fh.updateRecord(fo,FilePath,updateStr,lineNum-1);
def deleteEmployee(self):
lineNum = input("Enter the line number of the entry you want to delete: ");
with open(FilePath,"r") as fo:
fh.deleteRecord(fo,FilePath,lineNum-1);
def main(self):
goOn = True;
employee = Employee();
while goOn:
choice = input("Press:\n1 to enter a new employee\n2 to search employee\n3 to update employee\n4 to delete employee\n0 to exit\n");
if(choice == 1):
employee.createEmployee();
elif(choice == 2):
employee.searchEmployee();
elif(choice == 3):
employee.updateEmployee();
elif(choice == 4):
employee.deleteEmployee();
elif(choice == 0):
goOn = False;
else:
print "Wrong Choice!!!";
emp = Employee();
emp.main();
Here I am importing this class:
class FileHandeling:
def createFile(fo,numOfRecords,data,counterFile):
#Getting the value of counter
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
#Taking input and writing to the file
for i in range(counter,numOfRecords+counter):
string = str(i)+data[i];
fo.write(string);
counter += 1;
#Writing back to counter the updated value.
fwc = open(counterFile,"w");
fwc.write(str(counter)+"\n");
fwc.close();
def readFile(fo,searchStr,criteria):
line = fo.readline();
string = [];
while line:
entries = line.split();
if(searchStr == entries[criteria]):
string.append(line);
line = fo.readline();
return string;
def printFile(fo):
fo.seek(0);
lines = fo.readlines();
print "The File: "
for line in lines:
print line;
def updateRecord(fo,fileLoc,updateStr,lineNum):
#Replacing the given record with he updated record and writing back to file
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines[lineNum]= updateStr;
for line in lines:
fwu.write(line);
fwu.close();
def deleteRecord(fo,fileLoc,lineNum):
#Deleting the record
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines.pop(lineNum);
#Correcting the Employee Ids and Writing Back to File
for line in lines:
entry1, entry2, entry3, entry4, entry5 = line.split();
entry1 = str(lines.index(line));
line = entry1+" "+entry2+" "+entry3+" "+entry4+" "+entry5+"\n";
fwu.write(line);
fwu.close();
#Reducing Counter value
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
fwc = open(counterFile,"w");
fwc.write(str(counter-1)+"\n");
fwc.close();
In this code I am trying to replicate a database with the help of file but my code gives error saying that 'module' object has no attribute 'createFile'. I also tried creating packages and doing like in java but then it started saying that ImportError: No module named src.fileManipulation. they were just my folders in which I was working and wanted them as packages so I put an __init__.py in them and the tutorials said that this will help in making packages but that didn't happen and since both my files were in same directory I imported it directly but now it gives attribute error and I don't know what that means. Please Help.
I have executed the code in Python default IDLE after correcting some print statements. I am using Python3 so used print (" "). And the result was an endless loop of
Wrong Choice!!!
Press:
1 to enter a new employee
2 to search employee
3 to update employee
4 to delete employee
0 to exit
My kind requtest to you is to revise Python once again.
Related
I have to write a code that does the following:
Create a menu with three options.
Print the subjects
Search for a subject
Q) Quit
Create a main() function
Prompt the user for a file name.
Prompt the user for an option from the menu.
Open the file and load the data into a list.
Option 1 should print all the school subjects in the list, under a title
Once all the records have been processed, print a count.
Option 2 should allow the user to search for a subject in the list.
Add exception handling. (add last)
Create your own text file, with a list of 10 or more school subjects.
Submit the program module(s) and the output.
For a bonus, create a second module and import it, or add a menu item to add names to the list and save the data to a new file.
I keep getting "file not found" and was wondering if anyone could help. I want to name the read file as subjects.txt
This is the code I have written:
#Display menu and ask for user to select option
def menu():
print('Enter "1" to print subjects')
print('Enter "2" to search subjects')
print('Enter "3" to add subject')
print('Enter "q" to quit')
option = input('Enter option: ')
return option.lower()
#Reading files
def read_subjects(file_name):
file1 = open(subjects, 'r')
return file1.readlines()
#Add new subjects
def write_to_file(file_name, subject):
current_lines = []
try:
current_lines = read_subjects(file_name)
except:
pass
current_lines.append(subject + '\n')
file1 = open(file_name, 'w')
file1.writelines(current_lines)
file1.close()
#Main function
def main():
correct_file_name = False
file_name = 'subjects'
subjects = []
# while loop to ensure a user selects an existing file with catch and try
while not correct_file_name:
file_name = input('Enter file name: ')
try:
subjects = read_subjects(subject)
correct_file_name = True
except:
print('Error file not found')
# while loop to implement contious flow of options
while True:
selected_option = menu()
# quit program
if selected_option == 'q':
quit()
# display subjects
if selected_option == '1':
print('Subjects')
# Strips the newline character
count = 0
for line in subjects:
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# search for a subject
if selected_option == '2':
subject = input('Search subject: ')
print('Subjects')
count = 0
for line in subjects:
striped_line = line.strip()
if subject.lower() in striped_line.lower() or striped_line.lower() in hobby.lower():
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# bonus add new hobbies
if selected_option == '3':
subject = input('Enter new hobby: ')
write_to_file('subjects.txt', subject)
# call main function
if __name__ == '__main__':
main()
I am trying to write a login function using python. However, I can't seem to write the code for checking the username and password against the ones stored in a file. The specific error is NameError: name 'adusername' is not defined. How do I fix this?
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.write(adusername)
adfile.write(",")
adfile.write(adpassword)
adfile.write("\n")
adfile.close()
def adminverification():
adun = input("Enter your username:")
adpw = input("Enter your password:")
adinfo = open("adlogindetails.txt", "r")
for line in adinfo:
adun, adpw = line.split(",")
if adun == adusername and adpw == adpassword:
print("Login successful!")
adminoptions()
else:
print("Incorrect username/password")
roleselection()
adminverification()
You have not declared adusername and adpassword in adminverification(). So, it is causing the error. If you want to use the variables from adminlogindetails(), change the variables name since you have stored the details in adlogindetails.txt.
The below code should be changed as line variable contains the already stored username and password:
adun, adpw = line.split(",")
Change above piece of code to the shown below:
adusername, adpassword = line.split(",")
you can use this:
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.writelines(adusername + ',' + adpassword )
adfile.close()
def adminverification():
adun = input("Enter your username:").strip()
adpw = input("Enter your password:").strip()
with open("adlogindetails.txt", "r") as f:
lines = f.readlines()
i = 0
for line in lines:
adusername, adpassword= line.split(",")
adusername = str(adusername).strip()
adpassword = str(adpassword).strip()
if (adun == adusername) and (adpw == adpassword):
print("Login successful!()")
adminoptions()
break
else:
i += 1
if i >= len(lines): #If no any match upto last line, this will be true
print("Incorrect username/password")
roleselection()
break
adminverification()
First of all you are not calling adminlogindetails().
Also adusername is a local variable and you should either make it global using global adusername in the adminlogindetails function or declare it outside of the functions in the global scope.
See this - https://www.w3schools.com/python/python_scope.asp
This line is your problem:
adun, adpw = line.split(",")
"adun" and "adpw" are your inputs and you are overwriting them. Replace with this and it will be ok:
adusername, adpassword = line.replace("\n", "").split(",")
Note: "\n" needs to be removed for your comparison to be ok.
#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.
I am working with an external file which has data in the form of:
-12345 CSEE 35000 Bart Simpson
-12346 CSEE 25000 Harry Potter
-12350 Economics 30000 Krusty The Clown
-13123 Economics 55000 David Cameron
With the first item being the ID, the second the subject, the third the salary, and the rest being the name of the person.
In part of my program I am trying to print the information of the people who have salaries between values submitted by the user. I have put all the data in a list called lecturers then I put all the salaries in a separate list called lecturers salary and tried to make them integers because at first I thought the reason the for loop wasn't working was because when trying to access them from the lectures loop I thought they might still be part of a string at this point.
I have already used a loop in my program to print all the people who teach a specific subject. This subject is submitted by the user. I tried to use a for loop again for the salaries but its not working.
print""
# To God be the Glory
lecturer = []
lecturer_salary = []
x = 0
a = " "
print ""
String = raw_input("Please enter the lecturers details: ")
print ""
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
ID_Subject = " ".join(String[0:2])
money = String[2]
print "%s,%s %s %s" % (lastname,firstnames,ID_Subject,money)
printFormat(String)
while x < len(lecturer):
lecturer_salary.append(int(lecturer [x][2]))
x = x + 1
print ""
try:
fname = input("Enter filename within " ": ")
with open(fname) as f:
for line in f:
data = line.split()
printFormat(line)
line = line.split()
lecturer.append(line)
except IOError as e :
print("Problem opening file")
print ""
print ""
answer = raw_input("Would you like to display the details of lectureers from a particular department please enter YES or NO: ")
if answer == "YES" :
print ""
department = raw_input("Please enter the department: ")
print ""
while x < len(lecturer) :
for line in lecturer:
if lecturer[x][1] == department:
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
**elif answer == "NO" :
print ""
answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")
print ""
if answer2 == "YES":
lower_bound = int(input("Please enter the lower bound of the salary range: "))
upper_bound = int(input("Please enter the upper bound of the salary range: "))
print ""
while x < len(lecturer) :
for line in lecturer_salary:
if lower_bound < lecturer_salary[x] < upper_bound :
print lecturer_salary[x]
x = x + 1**
else:
print ""
print "Please enter a valid input"
So, you have an array of lecturer and one of lecturer salary. the
for line in lecturer_salary:
is not needed - just the while followed by the if. Note that this will only print out the salary, not the lecturer details. Since x is the index to both arrays you can access lecturer[x] for the rest. In truth you don't need the lecturer_salary at all, just walk through lecturer and check:
while x < len(lecturer) :
if lower_bound < lecturer[x][2] < upper_bound :
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
For starters, you shouldn't name your variable with a capital letter like String or Id_Subject.
It is simpler to break code into functions and try using a dictionary or class to improve readability and extensibility.
Here is a minimal code using class:
lecturers = [] # To store Lecturer instances, which isn't necessary
class Lecturer():
def __init__(self, id, subject, salary, name):
self.id = id
self.subject = subject
self.salary = salary
self.name = name
def readfile(filename):
"""read each line in a file and yield a list of fields"""
with open(filename, "r") as f:
for line in f.readlines():
# return a list of fields
yield line.replace("\n", "").split()
def new_lecturer(detail):
"""Return a new lecturer instance from a list of fields"""
return Lecturer(detail[0],
detail[1],
detail[2],
{"firstname": detail[3],
"lastname": detail[4]
})
def print_lecturer_detail(lecturer):
"""Accept a lecturer instance and print out information"""
print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
lecturer.name["firstname"],
lecturer.id,
lecturer.salary)
def main():
"""This is where all the main user interaction should be"""
fname = raw_input("Enter filename: ")
for lecturer in (readfile(fname)):
lecturers.append(new_lecturer(lecturer))
print ""
answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")
if answer == "Y":
print ""
department = raw_input("Please enter the department: ")
print ""
for lecturer in lecturers:
if lecturer.subject == department:
print_lecturer_detail(lecturer)
elif answer == "N":
# implement salary code here
pass
if __name__ == '__main__':
main()
This may be an overkill now, but it's better than dealing with lists in a long run. You'll see that dealing with properties become much simpler. You may want to improve each function further and make it more modular and reusable.
#Paul Morrington has the straight answer on the while part.
I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.
My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.
The records should look like this:
name,score,score,score,score,
etc so they can be split using commas.
I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
EDIT:
Add this function before your "test" function:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
After that, where you have "if users_class == 1:" do this:
writeUserScore("Class1.txt", username, str(correct_answers))
Do the same for the other two else ifs.
Let me know what you think!
Try using a dictionary to hold the existing file data.
Read the file in a variable called "str" for example. And then do something like this:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
When you have a new score you should then do:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
And to save the data back to the file:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
And save the contents of "output" to the file.
PS: If you are not bound by the file format you can use a JSON file. I can tell you more about this if you wish.
Hope that helps,
Alex
First, define these functions:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Now, in the last portion of your code (where you actually write the scores out) becomes much simpler. Here's an example of writing some scores:
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)
there will be two lines in Class1.txt:
phil,7,6,9
alice,6
We read the whole file into a dict (actually a defaultdict(list)),
and overwrite that same file with an updated dict. By using defaultdict(list), we don't have to worry about distinguishing between updating and adding a record.
Note also that we don't need separate if/elif cases to read/write the files. "Scores%d.txt"%users_class gives us the name of the file.