python help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manchesterboy
    New Member
    • May 2010
    • 7

    python help

    When i do the add_player statement, it doesn't want to edit the current ppp.txt file. When i list the players currently in the ppp.txt file its seems ok, its just adding a new player doesnt seem to work.

    Code:
    players=open("ppp.txt","r")
    
    
    lis=[]
    
    
    for line in players:
                line=line.strip()
                x=line.split(";")
             
                p=Person()
                p.surname=x[0]
                p.forename=x[1]
                p.email=x[2]
                p.phonenum=x[3]
                p.current_div=x[4]
                p.current_points=x[5]
                p.prev_div=x[6]
                p.prev_points=x[7]
                lis.append(p)
                for p in lis:
                    
                    print "%6s%12s%25s%14s%10s%10s%18s%15s"%(p.surname,p.forename,p.email,p.phonenum,p.current_div,p.current_points,
                    p.prev_div,p.prev_points)
    
    players.close()
                
    
            
    
    
    def add_player(surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points):  
        '''
        This function allows the user to add another player to the text file
            surname=surname of player
            forename=forename of the player 
            email=email of player
            phonenum=phonenum of player
            current_div= the current division for the player
            current_points=current points of the player
            prev_div=the previous division of the palyer
            prev_points=the previous points of the player
        '''
        
        lis.append([surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points])
    
    add_player("j","k","L","1","2","3","4","5")
    Thanks is advance for your help, its much appreciated.
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Originally posted by manchesterboy
    Hi all.
    I'm currently doing coursework for my university, and im struggling with a bit of the code.

    when i do the add_player statement, it doesn't want to edit the current ppp.txt file. When i list the players currently in the ppp.txt file its seems ok, its just adding a new player doesnt seem to work.

    Code:
    players=open("ppp.txt","r")
    
    
    lis=[]
    
    
    for line in players:
                line=line.strip()
                x=line.split(";")
             
                p=Person()
                p.surname=x[0]
                p.forename=x[1]
                p.email=x[2]
                p.phonenum=x[3]
                p.current_div=x[4]
                p.current_points=x[5]
                p.prev_div=x[6]
                p.prev_points=x[7]
                lis.append(p)
                for p in lis:
                    
                    print "%6s%12s%25s%14s%10s%10s%18s%15s"%(p.surname,p.forename,p.email,p.phonenum,p.current_div,p.current_points,
                    p.prev_div,p.prev_points)
    
    players.close()
                
    
            
    
    
    def add_player(surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points):  
        '''
        This function allows the user to add another player to the text file
            surname=surname of player
            forename=forename of the player 
            email=email of player
            phonenum=phonenum of player
            current_div= the current division for the player
            current_points=current points of the player
            prev_div=the previous division of the palyer
            prev_points=the previous points of the player
        '''
        
        lis.append([surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points])
    
    add_player("j","k","L","1","2","3","4","5")
    Thanks is advance for your help, its much appreciated.
    But your add function just appends it to the list called lis. You don't write it to the file at all!

    You need to create a string from the data in the right format for your file (separated by semi-colons etc), and then write it to file. You could probably use the append mode, so something like this:

    Code:
    players=open("ppp.txt","a")
    players.write(theStringOfYourData)
    players.close()

    Comment

    • manchesterboy
      New Member
      • May 2010
      • 7

      #3
      Im new to the programming, so its taking me some time to get used to it
      my ppp.txt file is written in the format:
      krapa;peter;p.k ;565;1;2;3;55
      for example.
      so to add the next player onto the text file i would need to do the following:
      players=open("p pp.txt","a") this allows me to append the file
      the players.write(w ould i use the (x[0],x[1]...) file(this bit is confusing me)
      then
      players.close()
      Its the players.write() bit. i am confused about, as it has not been covered in our lectures.
      thanks for your help

      Comment

      • Nonemsludo
        New Member
        • Apr 2010
        • 15

        #4
        You say you already have the file open it for reading and writing or for writing only with "r+" or "w"
        Code:
        players=open("ppp.txt","r+"or "w")
        players.write(theStringOfYourData)
        players.close()

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Originally posted by manchesterboy
          Im new to the programming, so its taking me some time to get used to it
          my ppp.txt file is written in the format:
          krapa;peter;p.k ;565;1;2;3;55
          for example.
          so to add the next player onto the text file i would need to do the following:
          players=open("p pp.txt","a") this allows me to append the file
          the players.write(w ould i use the (x[0],x[1]...) file(this bit is confusing me)
          then
          players.close()
          Its the players.write() bit. i am confused about, as it has not been covered in our lectures.
          thanks for your help
          The answer is "it depends". One of the things about python (and other dynamically typed languages if that's the right terminology) is that variables can be any type (string, integer, float, list, user-defined class, etc) and can flit from one to the other. When you write to a file it needs to be a string. So if your variable is a string already, then fine, otherwise you need to convert it.

          You had this line:
          Code:
          add_player("j","k","L","1","2","3","4","5")
          which suggests that all your variables are strings.

          You could code it like this:
          Code:
          players.write(x[0]+";"+x[1]+";"+...)
          or like this:
          Code:
          players.write("%s;%s;%s;..."%(x[0],x[1],...)
          or, if the above looked like too much typing you could build up the string like this:
          Code:
          s=""
          for item in x[:-1]:
              s+=item+";"
          s+=x[-1]
          players.write(s)
          and there's probably more compact ways of doing this with list comprehensions.

          Comment

          • manchesterboy
            New Member
            • May 2010
            • 7

            #6
            thanks for the help!
            my code now looks like thin
            Code:
            class Person(object):
                '''
                my list of squash players
                '''
            
            
            players=open("ppp.txt","r")
            
            
            lis=[]
            
            
            for line in players:
                        line=line.strip()
                        x=line.split(";")
                     
                        p=Person()
                        p.surname=x[0]
                        p.forename=x[1]
                        p.email=x[2]
                        p.phonenum=x[3]
                        p.current_div=x[4]
                        p.current_points=x[5]
                        p.prev_div=x[6]
                        p.prev_points=x[7]
                        lis.append(p)
                        for p in lis:
                            
                            print "%6s%12s%25s%14s%10s%10s%18s%15s"%(p.surname,p.forename,p.email,p.phonenum,p.current_div,p.current_points,
                            p.prev_div,p.prev_points)
            
            players.close()
                        
            
                    
            
            
            
            
            def add_player(surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points):  
                '''
                This function allows the user to add another player to the text file
                    surname=surname of player
                    forename=forename of the player 
                    email=email of player
                    phonenum=phonenum of player
                    current_div= the current division for the player
                    current_points=current points of the player
                    prev_div=the previous division of the palyer
                    prev_points=the previous points of the player
                '''
                
                lis.append([surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points])
                
            
            players=open("ppp.txt","a")
            add_player("franks","david","[email protected]","0445554","1","2","3","4")
            players.write("%s;%s;%s;%s;%s;%s;%s;%s"%(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]))
            players.close()
            There now appears to be another problem:
            The code doesn't write the new player into the text file, instead it seems to duplicate the player already in the text file, and just add it again.

            I am confused as to why this is, as surely the add_player definition appends the list to add the player into it.
            sorry if this problem seems trivial, i have never done programing before now, and its a steep learning curve
            Thanks again

            Comment

            • Glenton
              Recognized Expert Contributor
              • Nov 2008
              • 391

              #7
              Originally posted by manchesterboy
              thanks for the help!
              my code now looks like thin
              Code:
              class Person(object):
                  '''
                  my list of squash players
                  '''
              
              
              players=open("ppp.txt","r")
              
              
              lis=[]
              
              
              for line in players:
                          line=line.strip()
                          x=line.split(";")
                       
                          p=Person()
                          p.surname=x[0]
                          p.forename=x[1]
                          p.email=x[2]
                          p.phonenum=x[3]
                          p.current_div=x[4]
                          p.current_points=x[5]
                          p.prev_div=x[6]
                          p.prev_points=x[7]
                          lis.append(p)
                          for p in lis:
                              
                              print "%6s%12s%25s%14s%10s%10s%18s%15s"%(p.surname,p.forename,p.email,p.phonenum,p.current_div,p.current_points,
                              p.prev_div,p.prev_points)
              
              players.close()
                          
              
                      
              
              
              
              
              def add_player(surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points):  
                  '''
                  This function allows the user to add another player to the text file
                      surname=surname of player
                      forename=forename of the player 
                      email=email of player
                      phonenum=phonenum of player
                      current_div= the current division for the player
                      current_points=current points of the player
                      prev_div=the previous division of the palyer
                      prev_points=the previous points of the player
                  '''
                  
                  lis.append([surname,forename,email,phone_num,current_div,current_points,prev_div,prev_points])
                  
              
              players=open("ppp.txt","a")
              add_player("franks","david","[email protected]","0445554","1","2","3","4")
              players.write("%s;%s;%s;%s;%s;%s;%s;%s"%(x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]))
              players.close()
              There now appears to be another problem:
              The code doesn't write the new player into the text file, instead it seems to duplicate the player already in the text file, and just add it again.

              I am confused as to why this is, as surely the add_player definition appends the list to add the player into it.
              sorry if this problem seems trivial, i have never done programing before now, and its a steep learning curve
              Thanks again
              Hi

              This is what your code does:
              1. Defines a Person class;
              2. Opens a file and creates a blank list (lis);
              3. Reads the file line by line into a Person object via a temporary list x;
              4. Appends each person object to lis (each time printing out the whole contents of lis);
              5. Defines a function which appends to a local variable (also called lis) which hasn't been defined. I think python will pick it up anyway, but it's a dangerous way to live, IMHO!
              6. Calls the function;
              7. Adds the temporary x variable left over from the last step of 3 to the file.

              You could use some structuring in your code! For example your Person class could have methods which returns the x variable or which takes a line from the file or returns a line to be written to the file or prints out a neat summary. It could also have the file name included which would allow you to read and write to the file.

              But if you let us know what your grand vision is, perhaps we can help more with the structuring.

              PS You're doing great! You're just going through the difficult transition from understanding the lines to understanding the structure. Or at least the first of those difficult transitions!

              Comment

              • manchesterboy
                New Member
                • May 2010
                • 7

                #8
                thanks for the reply.
                My grand vision is as follows:
                to make a text file of players, that then can then be edited, by adding/removing players etc
                to get the text to print out the players, say in order of highest points, that can then be put into leagues etc.
                to allows the user to maybe just look at one player in particular.
                thats basically the programme i want to create.
                Thanks

                Comment

                • Glenton
                  Recognized Expert Contributor
                  • Nov 2008
                  • 391

                  #9
                  Okay. I suggest you get a text based one going first, and bolt the GUI on later. Much like you're trying to do, in fact.

                  You might want to think about one of the sql interfaces? But this is possibly too sophisticated for what you're trying to do. In fact there are probably several open source off-the-shelf things that achieve this kind of thing!

                  BUT...if you want to do it this way (and who wouldn't), we need to give some thought to structure. I'll try to have a think and post back. Let us know how it goes.

                  Oh, wait - this is for course work, not for real. Ah. That's different... I guess you'll have to come back with some questions!
                  Last edited by Glenton; May 19 '10, 02:19 PM. Reason: Re read first post!

                  Comment

                  • manchesterboy
                    New Member
                    • May 2010
                    • 7

                    #10
                    The main point of this programme is to allow a use to edit a text file, , which contains players in it.
                    I have code sort of written, however we are told that using classes is much better. Basically, i want to transfrer this code
                    Code:
                    '''
                    code to maintain a list of squash players
                    '''
                    playersFin=open("players.txt","r")
                    
                    
                    def add_player(Surname,Forname,email,phone_num,current_division,points_current,prev_div,prev_points):
                        '''
                        Add a player to the bottom league
                        '''
                        players.append([Surname,Forname,email,phone_num,current_division,points_current,prev_div,prev_points])
                        
                    def list_players():
                        '''
                        prints out the players in a list
                        '''
                        print "Surname   Forname        email                phone no.     current div   current points   previous div   previous points"
                        for player in players:
                                print "%6s%10s%25s%14s%10s%10s%18s%15s"%(player[0],player[1],player[2],player[3],player[4],player[5],player[6],player[7])
                    
                    def read_players( filename ):
                        '''
                        Open a file in the format:
                        Surname,Forname,email,phone_num,current_division,_points_current,prev_div,prev_points
                        each line is then added to the players list
                        The file is then closed
                        '''
                        f=open(filename,"r")
                        for line in f:
                            lis=line.split(";")
                            Surname=lis[0]
                            Forname=lis[1]
                            email=lis[2]
                            phone_num=lis[3]
                            current_division=int(lis[4])
                            points_current=int(lis[5])
                            prev_div=int(lis[6])
                            prev_points=int(lis[7])
                            add_player(Surname,Forname,email,phone_num,current_division,points_current,prev_div,prev_points)
                        f.close()
                        
                        
                    def write_players( filename ):
                        '''
                        Opens the file and writes out all the data
                        '''
                        f = open( filename , "w" )
                        for p in players:
                            f.write( "%s;%s;%s;%s;%d;%d;%d;%d\n" % (p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]))
                        f.close()
                          
                    def delete_players(Surname):
                        '''
                        deletes a player from the list
                        '''
                       
                        
                        for j in range (0,len(players)):
                    	if players[j][0]==Surname:
                    		del players[j]
                    		break
                    
                    
                    
                    def order_players():
                        
                    players=[]
                    read_players( "players.txt" )
                            
                    print
                    into a code the produces the same results, however is using classes. This is where i get horribly stuck!
                    Thanks

                    Comment

                    • Glenton
                      Recognized Expert Contributor
                      • Nov 2008
                      • 391

                      #11
                      What have you tried so far? Broadly, what you're probably going to want to do is:

                      1. Define a Player class, which stores all the players details. In here you can have methods for manipulating the data. Eg a method to add the details in a list, a method to add the details in a line from the file, a method for printing the details, or returning the details in a line that will go into the file etc.

                      2. Define a Players or Database class (or whatever you're going to call it). Each object of this class is a Database (so you might anticipate only having one instance of it, but that's okay). Then initialise the Database with a file name. Store the file name as an instance variable, and maybe make a list of players.

                      I guess you could do it without the first class if you wanted.

                      Anyway, most of your methods just become class methods.

                      Comment

                      • manchesterboy
                        New Member
                        • May 2010
                        • 7

                        #12
                        so something along these lines
                        Code:
                        playersFin=open("players.txt","r")
                        
                        
                        class Player(object):
                            '''
                            A squash player
                            '''
                            
                            def __init__(self,surname,forename,email,phone,currdiv,currpoints,prevdiv,prevpoints):
                                self.surname=surname
                                self.forename=forename
                                self.email=email
                                self.phone=phone_number
                                self.currdiv=currentddiv
                                self.currpoints=currentpoints
                                self.prevdiv=prevdiv
                                self.prevpoints=prevpoints
                         
                        
                            
                            def add_player(self):
                                '''
                                adds player to the list
                                '''
                                players.append([self.surname,self.forename,self.email,self.phone,self.currdiv,
                                self.currpoints,self.prevdiv,self.prevpoints])
                            
                                
                        class Database(object):
                        
                        
                        
                        
                            
                        
                        
                        
                        players=[]
                        however i am now back to struggling with the gritty code to make it all work smoothly!

                        Comment

                        • Glenton
                          Recognized Expert Contributor
                          • Nov 2008
                          • 391

                          #13
                          So I was thinking more like this for the Player object

                          Code:
                          class Player(object):
                              '''
                              A squash player
                              '''
                           
                              def __init__(self,surname=None,forename=None,email=None,phone=None,
                          currdiv=None,currpoints=None,prevdiv=None,prevpoints=None):
                                  if surname:
                                      self.surname=surname
                                      self.forename=forename
                                      self.email=email
                                      self.phone=phone_number
                                      self.currdiv=currentddiv
                                      self.currpoints=currentpoints
                                      self.prevdiv=prevdiv
                                      self.prevpoints=prevpoints
                           
                           
                           
                              def add_player(self,textstring):
                                  '''
                                  adds player to the list
                                  '''
                                  #Do whatever stripping and spliting to extract the relevant data from the 
                                  #textstring, and then set the players attributes to this
                                  self.surname=...
                          
                              def get_file_string(self):
                                  str=""
                                  if self.surname: str+=self.surname
                                  if self.forename: str+=self.forename
                                  etc...
                                  return str
                          
                              def get_list(self):
                                  return [self.surname,self.forename,...]

                          Comment

                          • manchesterboy
                            New Member
                            • May 2010
                            • 7

                            #14
                            So, i have edited the code, and it makes sense, sort of.
                            However i need to utilise the text file that consists of the players that are already in the 'database'

                            Code:
                            class Player(object):
                            playersFin=open("players.txt","r")
                                '''
                                A squash player
                                '''
                             
                                def __init__(self,surname=None,forename=None,email=None,phone=None,
                            currdiv=None,currpoints=None,prevdiv=None,prevpoints=None):
                                    if surname:
                                        self.surname=surname
                                        self.forename=forename
                                        self.email=email
                                        self.phone=phone_number
                                        self.currdiv=currentddiv
                                        self.currpoints=currentpoints
                                        self.prevdiv=prevdiv
                                        self.prevpoints=prevpoints
                             
                             
                             
                                def add_player(self,textstring):
                                    '''
                                    adds player to the list
                                    '''
                                    for line in players:
                                        line=line.strip()
                                        x=line.split(";")
                                        self.surname=x[0]
                                        self.forename=x[1]
                                        self.email=x[2]
                                        self.phone=x[3]
                                        self.currdiv=x[4]
                                        self.currpoints=x[5]
                                        self.prevdiv=x[6]
                                        self.prevpoints=x[7]
                                            
                                            
                             
                                def get_file_string(self):
                                    str=""
                                    if self.surname: str+=self.surname
                                    if self.forename: str+=self.forename
                                    if self.email: str+=self.email
                                    if self.phone: str+=self.phone
                                    if self.currdiv: str+=self.currdiv
                                    if self.currpoints: str+=self.currpoints
                                    if self.prevdiv: str+=self.prevdiv
                                    if self.prevpoints: str+=self.prevpoints
                                    return str
                             
                                def get_list(self):
                                    return [self.surname,self.forename,self.email,self.phone,self.currdiv,self.currpoints,
                                    self.prevdiv,self.prevpoints]
                            i have imported the text file playersFin
                            i now need to edit the code i have written, to allow me the add a player to the text file, then also allow me to delete a player, and if possible list the player according to their current point etc.
                            Thanks again for you help

                            Comment

                            • Glenton
                              Recognized Expert Contributor
                              • Nov 2008
                              • 391

                              #15
                              Originally posted by manchesterboy
                              So, i have edited the code, and it makes sense, sort of.
                              However i need to utilise the text file that consists of the players that are already in the 'database'

                              Code:
                              class Player(object):
                              playersFin=open("players.txt","r")
                                  '''
                                  A squash player
                                  '''
                               
                                  def __init__(self,surname=None,forename=None,email=None,phone=None,
                              currdiv=None,currpoints=None,prevdiv=None,prevpoints=None):
                                      if surname:
                                          self.surname=surname
                                          self.forename=forename
                                          self.email=email
                                          self.phone=phone_number
                                          self.currdiv=currentddiv
                                          self.currpoints=currentpoints
                                          self.prevdiv=prevdiv
                                          self.prevpoints=prevpoints
                               
                               
                               
                                  def add_player(self,textstring):
                                      '''
                                      adds player to the list
                                      '''
                                      for line in players:
                                          line=line.strip()
                                          x=line.split(";")
                                          self.surname=x[0]
                                          self.forename=x[1]
                                          self.email=x[2]
                                          self.phone=x[3]
                                          self.currdiv=x[4]
                                          self.currpoints=x[5]
                                          self.prevdiv=x[6]
                                          self.prevpoints=x[7]
                                              
                                              
                               
                                  def get_file_string(self):
                                      str=""
                                      if self.surname: str+=self.surname
                                      if self.forename: str+=self.forename
                                      if self.email: str+=self.email
                                      if self.phone: str+=self.phone
                                      if self.currdiv: str+=self.currdiv
                                      if self.currpoints: str+=self.currpoints
                                      if self.prevdiv: str+=self.prevdiv
                                      if self.prevpoints: str+=self.prevpoints
                                      return str
                               
                                  def get_list(self):
                                      return [self.surname,self.forename,self.email,self.phone,self.currdiv,self.currpoints,
                                      self.prevdiv,self.prevpoints]
                              i have imported the text file playersFin
                              i now need to edit the code i have written, to allow me the add a player to the text file, then also allow me to delete a player, and if possible list the player according to their current point etc.
                              Thanks again for you help
                              This doesn't make sense to me. What is the Player object? A single player, or a database of players?

                              What I had intended was that it was a single player, and that another class structure would be used for the database (which will handle the file too). In the current situation you go through the file and over-write the single player with each new line. In the end you'll just have the last player - all the others will have been over-written.

                              My intention with the get_file_string method is that it will return the line for the player, so in this case it needs to have the semi-colons or whatever separator you're using between the bits.

                              Anyway, however you do it is up to you. My point is that you need to have it clear in your mind what is going to do what. And, if you want effective help, communicate that plan!

                              Comment

                              Working...