writing files in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kasrav
    New Member
    • Apr 2007
    • 16

    writing files in python

    Hey there its me again i got this program but i have to improve on it but i am stuck hopefully you can help here is the code
    [CODE=python]
    def student():
    welcome();
    info = [ ]

    print "Creating a file studentHND.txt to write to: \n";
    output = open("studentHN D.txt","w");
    for i in range(5):
    name = raw_input('Plea se enter name: ');
    python = validate('Pleas e enter mark for pythod: ');
    aandd = validate('Pleas e enter mark for aandd: ');
    learn = validate('Pleas e enter mark for learn: ');
    info.append(nam e)
    info.append(pyt hon)
    info.append(aan dd)
    info.append(lea rn)

    output.write(st r(name)+','),ou tput.write(str( python)+'in PYTHOD,'),outpu t.write(str(aan dd)+'in AANDD,'), 'and',output.wr ite(str(learn)+ 'in Learn'),"\n";

    print "\nOperatio n complete"
    output.close();





    def validate(prompt ):
    limit = input(prompt);
    while(True):
    if (limit>=0 and limit<=100):
    return limit;
    else:
    print limit, "invalid"
    limit = input(prompt);


    def welcome():
    print "This program opens and write information into a file"
    print '************** *************** *************** *************** ******'
    [/CODE]
    Basically to improve on it i have to wirte a program which records data from the file created in the above exercise and it should calculate and print out the following:

    the name of each student, and which units, if any, they failed(ie a mark under 40). If they failed nothing i should report that as well.

    the average score for each unit and which unit achieved the highest average
    Thanks
    Last edited by bartonc; Jun 28 '07, 09:15 PM. Reason: Added [CODE=python][CODE] tags.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Originally posted by Kasrav
    Hey there its me again i got this program but i have to improve on it but i am stuck hopefully you can help here is the code
    [CODE=python]
    def student():
    welcome();
    info = [ ]

    print "Creating a file studentHND.txt to write to: \n";
    output = open("studentHN D.txt","w");
    for i in range(5):
    name = raw_input('Plea se enter name: ');
    python = validate('Pleas e enter mark for pythod: ');
    aandd = validate('Pleas e enter mark for aandd: ');
    learn = validate('Pleas e enter mark for learn: ');
    info.append(nam e)
    info.append(pyt hon)
    info.append(aan dd)
    info.append(lea rn)

    output.write(st r(name)+','),ou tput.write(str( python)+'in PYTHOD,'),outpu t.write(str(aan dd)+'in AANDD,'), 'and',output.wr ite(str(learn)+ 'in Learn'),"\n";

    print "\nOperatio n complete"
    output.close();





    def validate(prompt ):
    limit = input(prompt);
    while(True):
    if (limit>=0 and limit<=100):
    return limit;
    else:
    print limit, "invalid"
    limit = input(prompt);


    def welcome():
    print "This program opens and write information into a file"
    print '************** *************** *************** *************** ******'
    [/CODE]
    Basically to improve on it i have to wirte a program which records data from the file created in the above exercise and it should calculate and print out the following:

    the name of each student, and which units, if any, they failed(ie a mark under 40). If they failed nothing i should report that as well.

    the average score for each unit and which unit achieved the highest average
    Thanks
    There are two things that you can do right away (until someone has some time to look at this):
    1) Start using CODE tags in your posts. Instructions are on the right hand side of the page while posting or replying. And since you have over 10 posts, I must tell you that you have been officially warned about using code tags. New site rules mandate a temporary ban on your account for such infractions. All site rules are posted in our Posting Guidelines.

    2) Stop putting semicolons at the end of lines (unless you really like looking at them). semicolon is used to separate multiple statements on one line (another discouraged practice).

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      Originally posted by Kasrav
      Hey there its me again i got this program but i have to improve on it but i am stuck hopefully you can help here is the code
      [CODE=python]
      def student():
      welcome();
      info = [ ]

      print "Creating a file studentHND.txt to write to: \n";
      output = open("studentHN D.txt","w");
      for i in range(5):
      name = raw_input('Plea se enter name: ');
      python = validate('Pleas e enter mark for pythod: ');
      aandd = validate('Pleas e enter mark for aandd: ');
      learn = validate('Pleas e enter mark for learn: ');
      info.append(nam e)
      info.append(pyt hon)
      info.append(aan dd)
      info.append(lea rn)

      output.write(st r(name)+','),ou tput.write(str( python)+'in PYTHOD,'),outpu t.write(str(aan dd)+'in AANDD,'), 'and',output.wr ite(str(learn)+ 'in Learn'),"\n";

      print "\nOperatio n complete"
      output.close();





      def validate(prompt ):
      limit = input(prompt);
      while(True):
      if (limit>=0 and limit<=100):
      return limit;
      else:
      print limit, "invalid"
      limit = input(prompt);


      def welcome():
      print "This program opens and write information into a file"
      print '************** *************** *************** *************** ******'
      [/CODE]
      Basically to improve on it i have to wirte a program which records data from the file created in the above exercise and it should calculate and print out the following:

      the name of each student, and which units, if any, they failed(ie a mark under 40). If they failed nothing i should report that as well.

      the average score for each unit and which unit achieved the highest average
      Thanks
      did you make this program or not? try to do it yourself first. if you are hit with a problem, then ask.

      Comment

      • Kasrav
        New Member
        • Apr 2007
        • 16

        #4
        I am really sorry its not that i havent read the post guidelines or am not bothered to put codes tags around my post. I have read the guideline posts about two times now and i am still trying to figure how to do it because everytime i try i fail. I have just read the guidelines again this morning and i am still a bit confused as to do it may be you can enlight me more. I apologise for anything wrong done.
        Thanks

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Originally posted by Kasrav
          I am really sorry its not that i havent read the post guidelines or am not bothered to put codes tags around my post. I have read the guideline posts about two times now and i am still trying to figure how to do it because everytime i try i fail. I have just read the guidelines again this morning and i am still a bit confused as to do it may be you can enlight me more. I apologise for anything wrong done.
          Thanks
          Kasrav - This is an opening code tag for Python: [code=Python]

          This is a closing code tag: [/c o d e]

          I added spaces in between the characters so the tags will display.

          Could you show us a complete sample data file? That would help us help you.

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by Kasrav
            I am really sorry its not that i havent read the post guidelines or am not bothered to put codes tags around my post. I have read the guideline posts about two times now and i am still trying to figure how to do it because everytime i try i fail. I have just read the guidelines again this morning and i am still a bit confused as to do it may be you can enlight me more. I apologise for anything wrong done.
            Thanks
            OK, you don't have to worry about being banned for this. It's nice to know that you are trying. It's OK if you make a mistake, too, because I can fix those. You also have 5 minutes to edit your post and there is a Preview Post button so you can see what it will look like before you Submit it. Also, the editor where you put you post in has all the controls you need to make the all kinds of tags. Make sure that "Enhanced Mode" is selected. The # icon makes code tags.

            It's a learning thing; just keep trying. Thanks,
            Barton

            Comment

            • Kasrav
              New Member
              • Apr 2007
              • 16

              #7
              [CODE=python]def student():
              welcome();
              info = [ ]

              print "Creating a file studentHND.txt to write to: \n";
              output = open("studentHN D.txt","w");
              for i in range(5):
              name = raw_input('Plea se enter name: ');
              python = validate('Pleas e enter mark for pythod: ');
              aandd = validate('Pleas e enter mark for aandd: ');
              learn = validate('Pleas e enter mark for learn: ');
              info.append(nam e)
              info.append(pyt hon)
              info.append(aan dd)
              info.append(lea rn)

              output.write(st r(name)+','),ou tput.write(str( python)+'in PYTHOD,'),outpu t.write(str(aan dd)+'in AANDD,'), 'and',output.wr ite(str(learn)+ 'in Learn'),"\n";

              print "\nOperatio n complete"
              output.close();




              def validate(prompt ):
              limit = input(prompt);
              while(True):
              if (limit>=0 and limit<=100):
              return limit;
              else:
              print limit, "invalid
              limit = input(prompt);

              def welcome():
              print "This program opens and write information into a file"
              print '************** *************** *************** *************** ******'


              student()
              [/CODE]

              this one i have tried to put the tags on in but i am confused as to how you make it look like a proper python document
              Last edited by bartonc; Jun 30 '07, 08:03 PM. Reason: Changed tags to [CODE=python][CODE] tags.

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                Great job! I've made the change and left a "reason for editing" at the bottom that explains it. It's hard to explain in a post because the parser eats up properly formatted tags.

                Comment

                • bartonc
                  Recognized Expert Expert
                  • Sep 2006
                  • 6478

                  #9
                  Code:
                  def student():
                      welcome();  
                      info = [ ]  
                      
                      print "Creating a file studentHND.txt to write to: \n";
                      output = open("studentHND.txt","w");  
                      for i in range(5):          
                          name = raw_input('Please enter name: ');
                          python = validate('Please enter mark for pythod: ');
                          aandd = validate('Please enter mark for aandd: ');
                          learn = validate('Please enter mark for learn: ');
                          info.append(name)
                          info.append(python)
                          info.append(aandd)
                          info.append(learn)
                          
                          output.write(str(name)+','),output.write(str(python)+'in PYTHOD,'),output.write(str(aandd)+'in AANDD,'), 'and',output.write(str(learn)+ 'in Learn'),"\n";
                  
                      print "\nOperation complete"                                                                            
                      output.close();
                  
                  
                  
                  
                  def validate(prompt):
                      limit = input(prompt);
                      while(True):
                          if (limit>=0  and limit<=100):
                              return limit;
                          else:
                              print limit, "invalid 
                              limit = input(prompt);
                  
                  def welcome():
                      print "This program opens and write information into a file"
                      print '*****************************************************************'
                  
                  
                  student()
                  But it looks like there are some bugs in the parser at the moment. I'm posting a copy to see the differences...

                  Definitely some thing wrong on our end. I'll report it and try to get it fixed.

                  Comment

                  • Kasrav
                    New Member
                    • Apr 2007
                    • 16

                    #10
                    hey there, sorry i took long to reply its just that i dnt have regular use of the net.
                    I just wanted to ask if i am going to get some help on this file problem, thanks

                    <Mod EDIT: pasting last submission here>
                    [Sorry, I though you were presenting working code because you did not explain any problem that you were having.][CODE=python]def student():
                    welcome();
                    info = [ ]

                    print "Creating a file studentHND.txt to write to: \n";
                    output = open("studentHN D.txt","w");
                    for i in range(5):
                    name = raw_input('Plea se enter name: ');
                    python = validate('Pleas e enter mark for pythod: ');
                    aandd = validate('Pleas e enter mark for aandd: ');
                    learn = validate('Pleas e enter mark for learn: ');
                    info.append(nam e)
                    info.append(pyt hon)
                    info.append(aan dd)
                    info.append(lea rn)

                    output.write(st r(name) + ','),output.wri te(str(python) + 'in PYTHOD,'),outpu t.write(str(aan dd)+'in AANDD,'), 'and',output.wr ite(str(learn)+ 'in Learn'),"\n";

                    print "\nOperatio n complete"
                    output.close();




                    def validate(prompt ):
                    limit = input(prompt);
                    while(True):
                    if (limit>=0 and limit<=100):
                    return limit;
                    else:
                    print limit, "invalid
                    limit = input(prompt);

                    def welcome():
                    print "This program opens and write information into a file"
                    print '************** *************** *************** *************** ******'


                    student()
                    [/CODE]

                    Comment

                    • bartonc
                      Recognized Expert Expert
                      • Sep 2006
                      • 6478

                      #11
                      [CODE=python]def student():
                      welcome();
                      info = [ ]

                      print "Creating a file studentHND.txt to write to: \n"
                      output = open("studentHN D.txt","w")
                      for i in range(5):
                      name = raw_input('Plea se enter name: ')
                      python = validate('Pleas e enter mark for pythod: ')
                      aandd = validate('Pleas e enter mark for aandd: ')
                      learn = validate('Pleas e enter mark for learn: ')
                      info.append(nam e)
                      info.append(pyt hon)
                      info.append(aan dd)
                      info.append(lea rn)
                      # I guess that you thought that you could use commas that way that print does; You can't.
                      # I've added spaces where strings were followed by commas.
                      output.write(st r(name) + ', ')
                      output.write(st r(python) + 'in PYTHOD, ' )
                      output.write(st r(aandd) + 'in AANDD,' + 'and ')
                      output.write(st r(learn)+ 'in Learn\n')

                      print "\nOperatio n complete"
                      output.close()
                      # I also remove all those extra semicolons; they're for separating multiple statements on one line.




                      def validate(prompt ):
                      limit = input(prompt);
                      while(True):
                      if (limit>=0 and limit<=100):
                      return limit;
                      else:
                      print limit, "invalid" # added closing quotes.
                      limit = input(prompt);

                      def welcome():
                      print "This program opens and write information into a file"
                      print '************** *************** *************** *************** ******'


                      student()
                      [/CODE]

                      Comment

                      • Kasrav
                        New Member
                        • Apr 2007
                        • 16

                        #12
                        sorry Barton i dint expalin myself well the program i posted is ok but the problem that i have is that i have to use it to write another program which records data from the file created(program ) and it should calculate and print out the following:

                        the name of each student, and which units, if any, they failed(ie a mark under 40). If they failed nothing i should report that as well.

                        the average score for each unit and which unit achieved the highest average

                        hope that makes my problem clear, thanks

                        Comment

                        • bartonc
                          Recognized Expert Expert
                          • Sep 2006
                          • 6478

                          #13
                          Originally posted by Kasrav
                          sorry Barton i dint expalin myself well the program i posted is ok but the problem that i have is that i have to use it to write another program which records data from the file created(program ) and it should calculate and print out the following:

                          the name of each student, and which units, if any, they failed(ie a mark under 40). If they failed nothing i should report that as well.

                          the average score for each unit and which unit achieved the highest average

                          hope that makes my problem clear, thanks
                          Here's the direction I think that you should go in order to create such a program:
                          1) Don't worry about storing in a text file just yet.
                          2) Extend your idea of use the info list (info.append(da ta)) to include the ability to retrieve the desired data and precess it.
                          2.5) Use paper and pencil to draw your data structure:
                          .. a list .. [of students]
                          .. a student.. {'ID':1, 'name':'barton' , 'python':1000}
                          (that sort of thing).
                          3) Once you have a program that can put more than one record into a list in memory and get the data out for display - maybe consider a list of dictionaries for your database structure -, then we'll work on saving that data to a file and retrieving it.

                          Comment

                          • bvdet
                            Recognized Expert Specialist
                            • Oct 2006
                            • 2851

                            #14
                            You should carefully consider Barton's suggestions since they are good ones. To help you with your problem, I would start by modifying your code a bit to get the output in a simpler form:[code=Python]def student():
                            welcome()

                            print "Creating a file studentHND.txt to write to: \n"
                            output = open(r"H:\TEMP\ temsys\studentH ND1.txt","w")
                            for i in range(5):
                            name = raw_input('Plea se enter name: ')
                            python = validate('Pleas e enter mark for pythod: ')
                            aandd = validate('Pleas e enter mark for aandd: ')
                            learn = validate('Pleas e enter mark for learn: ')

                            output.write(', '.join([name, python, aandd, learn])+'\n')

                            print "\nOperatio n complete"
                            output.close()

                            def validate(prompt ):
                            limit = int(raw_input(p rompt))
                            while(True):
                            if (limit>=0 and limit<=100):
                            return str(limit)
                            else:
                            print limit, "invalid"
                            limit = raw_input(promp t)

                            def welcome():
                            print "This program opens and write information into a file"
                            print '************** *************** *************** *************** ******'

                            student()[/code]The data file will look like this:

                            Jeff Smith, 45, 80, 60
                            Bill Jones, 60, 90, 80
                            Cindy Hill, 90, 99, 78
                            Andy Miller, 39, 99, 80
                            Fred Taylor, 45, 66, 77

                            The following code will read the data file and create a dictionary in memory:[code=Python]# read data file and calculate statistics
                            # Unit hash table
                            unitDict = {0: 'pythod', 1: 'aandd', 2: 'learn'}

                            fn = r'H:\TEMP\temsy s\studentHND.tx t'

                            lineList = [item.strip().sp lit(',') for item in open(fn).readli nes() if item != '\n']

                            # Name list
                            keys = [i[0] for i in lineList]
                            # Scores list
                            values = [[int(s) for s in item] for item in [j[1:] for j in lineList]]

                            # Create a dictionary - Names are dictionary keys, score lists are the values
                            dataDict = dict(zip(keys, values))[/code]The dictionary looks like this:[code=Python]>>> dataDict
                            {'Jeff Smith': [45, 80, 60], 'Andy Miller': [39, 99, 80], 'Cindy Hill': [90, 99, 78], 'Fred Taylor': [45, 66, 77], 'Bill Jones': [60, 90, 80]}[/code]To access individual elements:[code=Python]>>> dataDict['Jeff Smith'][0]
                            45
                            >>> unitDict[0]
                            'pythod'
                            >>> [/code]Here's a little interaction:[code=Python]>>> for name in dataDict:
                            ... for i, score in enumerate(dataD ict[name]):
                            ... print "%s %s %d" % (name, unitDict[i], score)
                            ...
                            Jeff Smith pythod 45
                            Jeff Smith aandd 80
                            Jeff Smith learn 60
                            Andy Miller pythod 39
                            Andy Miller aandd 99
                            Andy Miller learn 80
                            Cindy Hill pythod 90
                            Cindy Hill aandd 99
                            Cindy Hill learn 78
                            Fred Taylor pythod 45
                            Fred Taylor aandd 66
                            Fred Taylor learn 77
                            Bill Jones pythod 60
                            Bill Jones aandd 90
                            Bill Jones learn 80
                            >>> [/code]From this you can determine the required statistics. We could do this for you, but it would be best if you could pick it up from here.

                            Comment

                            • Kasrav
                              New Member
                              • Apr 2007
                              • 16

                              #15
                              thanks once again u guys

                              Comment

                              Working...