Атрибут отсутствует - PullRequest
       19

Атрибут отсутствует

0 голосов
/ 03 декабря 2018

Я новичок в python и получаю ошибку атрибута.

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();

Здесь я импортирую этот класс:

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();

В этом коде я пытаюсь повторитьбаза данных с помощью файла, но мой код выдает ошибку, говорящую, что 'module' object has no attribute 'createFile'.Я также пытался создавать пакеты и делать как в Java, но потом он начал говорить, что ImportError: No module named src.fileManipulation.они были просто моими папками, в которых я работал, и хотели, чтобы они были пакетами, поэтому я добавил в них __init__.py, и в руководствах говорилось, что это поможет в создании пакетов, но этого не произошло, и так как оба моих файла были в тот же каталог Я импортировал его напрямую, но теперь он выдает ошибку атрибута, и я не знаю, что это значит.Пожалуйста, помогите.

1 Ответ

0 голосов
/ 03 декабря 2018

Я выполнил код в Python IDLE по умолчанию после исправления некоторых операторов печати.Я использую Python3, поэтому использовал print ("").В результате получился бесконечный цикл

Wrong Choice!!!
Press:
1 to enter a new employee
2 to search employee
3 to update employee
4 to delete employee
0 to exit

. Я хотел бы еще раз пересмотреть Python.

...