Sunday, May 30, 2010

StudyNote--V Python I

#<Copyright by sksc.me>
#<No one can copy and paste these codes without permission by sksc.me before 1st June 2010>
import os
import sys
def readlines(filename):
    """
    This function returns a list of all lines in a file and ignore those
    lines that begin with #
    """
    path=open(filename)
    p=[]
    for item in path :
        if not item.startswith('#'):#This is to ignore the line which starts with '#'
            p.append(item.strip())
#This is the ignore the whilespace at the beginning and the end of the string
    path.close()
    return p
def readtable(filename):
    """
    Reads a file of colon-delimited lines and returns a list of lists,with
    each lines being represented as a list of string,split on colons
    """
    path=open(filename)
    BigP=[]
    for item in path :
        if not item.startswith('#'):
            BigP.append(item.split(':'))# split on colons
    for itemX in range(len(BigP)):
 # This loop is to ignore the whitespace in each element
        for itemY in range(len(BigP[itemX])):
            BigP[itemX][itemY]=BigP[itemX][itemY].strip()
    path.close()
    return BigP
def writelines (filename,lines):
    """
    This function writes a list of string sately to the file filename,replacing
    any content already there.In this function a temp file is used in case of
    unsafely action.
    """
    try:
        path=open('temp.SHA','w')
        for x in lines :
            path.write(x+'\n')
        path.close()
        if os.path.isfile(filename):
            os.rename(filename,'InCase.SHA')
            os.rename('temp.SHA',filename)
            os.remove('InCase.SHA')
            return 1
        else :
            os.rename('temp.SHA',filename)
            return 1
    except:
        os.remove('temp.SHA')
        os.rename('InCase.SHA',filename)
        return 0
class Enrol:
    def __init__(self,Directory):
        """
        This is the constructor.Accepts the name of the directory where the
        enrolment data is kept.And it reads data from the directory
        """
        self.__dir=Directory
        self.__readFiles()
    def __readFiles(self):
        """
        This is the function for reading data when object is constructed,it is
        invoked by __init__.And it will throw Exception when some error happens.
        It reads all data including three main files and all .roll files,if .roll
        does not exsit, it will create a new one and read it.
        """
        self.__dict={}
        try:
            self.__SubjectData=readtable(self.__dir+'//SUBJECTS')
            self.__ClassData=readtable(self.__dir+'//CLASSES')
            self.__VenuesData=readtable(self.__dir+'//VENUES')
            for readFilesX in self.__ClassData :
                if not os.path.isfile(self.__dir+'//'+readFilesX[0]+'.roll'):
                                      ClassFile=open(self.__dir+'//'+readFilesX[0]+'.roll','w')
                                      ClassFile.close()# If the file does not exist, create one
                self.__dict[readFilesX[0]]=readlines(self.__dir+'//'+readFilesX[0]+'.roll')
            return 1
        except:
            print 'No Data Files Found'
            os._exit(1)# If any error happens during this step, exit the program
    def subjects(self):
        """
        This functio returns a list of subject codes handled by the enrolment
        system and accept no argument.
        """
        p=[]
        for subjectsX in self.__SubjectData :
            p.append(subjectsX[0])
        return p
    def subjectName(self,SubjectCode):
        """
        Accept a subject code and return the name of the subject with that code,
        and None will be returned if no subject name found
        """
        for subjectNameX in self.__SubjectData :
            if subjectNameX[0]==SubjectCode :
                return subjectNameX[1]
        return None
    def classes(self,SubjectCode):
        """
        Return a list of classIDs for a particular subject.Accept one argument:
        the subject code of a subject.And it will raise KeyError if the subject
        does not exist and return 0.
        """
        try:
            p=[]
            for classesX in self.__ClassData :
                if classesX[1]==SubjectCode :
                    p.append(classesX[0])
            if len(p):
                return p
            else :
                raise KeyError  #raise KeyError if the file is not there
        except KeyError:
            return 0  #catch the KeyError and return 0
    def classInfo(self,ClassID):
        """
        Accept a string of ClassID and return information about a certain class.
        And it will Raise KeyError if the class does not the exist and return 0.
        """
        try:
            P=[]
            Status=False
            for classInfoX in self.__ClassData :
                if classInfoX[0]==ClassID :
                    Status=True
                    break
            if not Status :
                raise KeyError
            return classInfoX[1],classInfoX[2],classInfoX[3],classInfoX[4],self.__dict[ClassID]
        except KeyError :
            return 0
    def checkStudent(self,StudentID,SubjectCode='a'):
        """
        Check which classes a student is enrolled in.Accept one or two arguments.
        The first one is StudentID and the second one is SubjectCode which is an
        option.If ano subjectCode is specified,it will return a list of class codes
        the student is enrolled in.Otherwise,it return class code of the class in
        which the student in enrolled for that subject.
        """
        p=[]
        try:
            if SubjectCode=='a' :
  # set SubjectCode a default value to help check whether how many arguments are given
                for checkStudentKey in self.__dict.keys():
                    for checkStudentX in self.__dict[checkStudentKey]:
                        if checkStudentX==StudentID:
                            p.append(checkStudentKey)
                            break
                return p
            else :
                ClassID=self.classes(SubjectCode)
                for checkStudentKey in ClassID :
                    for checkStudentX in self.__dict[checkStudentKey]:
                        if checkStudentX == StudentID:
                            p.append(checkStudentKey)
                            break
                return p
        except:
            return 0
    def enrol(self,StudentID,ClassID):
        """
        Attempt to enrol a student in a class.Accept StudentID and ClassCode.
        It will return 1 if success and 0 if fails.Before attempting to enrol
        a student in a class,it attempt to check whether there is still enough
        room to accept a student.If not, it fails.If yes,it proceeds.If the
        student is enrolled in any othrt classes in the same subject as the class,
        the old enrollment will be removed and replaced by a new one.
        """
        try:
            if self.classInfo(ClassID)==0:# invoke a def to check whether the ClassID is a right one
                return 0
            else:
                for enrolX in self.__dict[ClassID]:
                    if enrolX == StudentID :
                        return 1
                for enrolY in self.__ClassData:
                    if enrolY[0] ==ClassID :
                        for enrolZ in self.__VenuesData:
                            if enrolZ[0]==enrolY[3] and str(len(self.__dict[ClassID]))==str(enrolZ[1]):
                                print 'The Class is full'
                                return 0
                self.__dict[ClassID].append(StudentID)
                self.__dict[ClassID].sort()
                for enrolX in self.__ClassData :
                    if enrolX[0] ==ClassID :
                        for enrolY in self.__ClassData :
                            if enrolY[1]==enrolX[1] and enrolY[0]!=ClassID :
                                self.__dict[enrolY[0]]=filter(lambda x: x!=StudentID,self.__dict[enrolY[0]])
                                #Delete the StudentID in any other class under same subject
                                self.__dict[enrolY[0]].sort()# sort them
                                FileNameX=self.__dir+'//'+ClassID+'.roll'
                                FileNameY=self.__dir+'//'+enrolY[0]+'.roll'
                                writelines(FileNameX,self.__dict[ClassID])
                                writelines(FileNameY,self.__dict[enrolY[0]])
                                return 1
        except:
            return 0

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home