1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Python File I/O Assignment headache

Discussion in 'Scripting & Programming' started by tripwire45, Mar 27, 2008.

  1. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    I really had high hopes of figuring this one out myself. It involves rewriting a prior code example to be able to write student grades to a file and to be able to read a file and load grade information. As an example, the author took a previous example involving phone numbers and rewrote it so name and phone number information could be read from and written to other files.

    My strategy was simple. I'd print out the author's "before and after" programs, compare what he did to change them, then take the "before" example for the student grades program and use the other two files as a basis for rewriting this program to include the additional functionality.

    I can't get it to work after 2 days and I've got other things to do with my life than bang my head against a brick wall. Rather than including four rather extensive programs in this post, I'm going to create 4 attachments.

    The samples I'm working from are:
    phone_list_before.txt
    phone_list_after.txt

    The sample I'm supposed to rewrite is:
    grades_before.txt

    The assignment I'm struggling with that I'm trying to rewrite from grades_before.txt is:
    grades_assignment.txt

    I'm saving them as txt files since I doubt the the CF forum software will recognize the .py extention. When you get the time, if you could take a look at what I'm trying to do and see if you could make some suggestions. Thanks. :oops:
     

    Attached Files:

    Certifications: A+ and Network+
  2. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Hi trip

    Sometimes programming assignments will take more than two days to crack; I'm assuming that you were given more time than two days to complete it? What does your tutor have to say regarding your problems?

    The code is a little large for a quick fix, so which part(s) are you having problems with?
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  3. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    The assignment is self imposed. I'm working off of Josh Cogliati's tutorial, "Non-Programmers Tutorial For Python". It's freely available in either HTML or PDF format from the web. He doesn't "support" the tutorial at this point, so there's no way to ask the author for assistance and the tutorial doesn't contain an answer key, so as far as solving problems, the reader is on their own.

    I know it's a lot to dump on the forum and expect a response, but I feel I've reached an impasse and need at least a clue to go on (not that I've stopped trying...I've just decided to take a break and work on a different problem before I start screaming). :tongue

    As I mentioned earlier, I'm trying to re-write grades_before.txt so that the grades for students created in the program can be written to an external file such using something like (and this is just an example from the phone_list_after.txt file):
    Code:
    def save_numbers(numbers,filename):
           out_file = open(filename,"w")
           for x in numbers.keys():
                out_file.write(x+","+numbers[x]+"\n")
           out_file.close()
    I also need to be able to use the program to access a text file and read that data into the program as in the following example, also from phone_list_after.txt:
    Code:
    def load_numbers(numbers,filename):
           in_file = open(filename,"r")
           while true:
                in_line = in_file.readline()
                if in_line == "":
                    break
                in_line = in_line[:-1]
                [name,number] = string.split(in_line,",")
                numbers[name] = number
           in_file.close()
    The problem is that I'm having trouble understanding how to write the sections that tell my program where to write to and where to read from. I thought that by comparing phone_list_before.txt and phone_list_after.txt, I'd be able to understand how the original program was rewritten to enable the phone list data to be read from another file and written to another file, then adapt that information to rewrite grades_before.txt so that when finished, grades_assignment.txt would be able to read and write student grade data from and to other files.

    Unfortunately, I'm not getting the hang of how to construct those portions of the program. I've been reduced to trial and error and have been receiving various different types of error messages when I actually try to write grade info to a file (I haven't even gotten to the point where I've tried to construct the "read from" part of the program yet).

    Yes, I understand that some troubleshooting and debugging tasks can take more than two days, but given the information I've been presented with, I thought I'd be further along than this. I did manage to get everything else to work (creating and removing students, adding grades, printing grades to the screen, printing the menu, and quitting the program), but these two areas have me stumped.

    As always, I'm looking for a bit of guidance to break the log jam in my brain. Any assistance is, as always, appreciated.

    Thanks.
     
    Certifications: A+ and Network+
  4. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    To be honest I can see a multitude of problems in your code. For instance:

    1. The way that you are contructing your strings is very error prone, for instance:

    Code:
        print "Name: ",x," \tNumber: ",numbers[x]
    
    should be

    Code:
        print "Name: %s \tNumber: %s" % (x, str(numbers[x]))
    
    2. Your use of dictionaries isn't right for the application at hand - possibly even redundant. This is quite in-depth, so I'll cover it later.
    3. It looks like you are referencing dictionaries without first checking that the key exists with has_key().
    4. Depending on whether you read your file line by line or in one go, a for-loop would have been a lot more suitable than a while-loop.
    5. I recall mentioning before on another thread that you should redefine 'true' or 'false', since Python has its own defined as 'True' and 'False'. Also in programming:

    Code:
       true: x not equal to 0
       false: x equals 0
    
    This is a very important principal for so many reasons in programming.

    The list goes on a little.

    If you give me the weekend I'll write a version that explains where yours has gone wrong.

    Is that okay?
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  5. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Believe me, I'm only grateful for the effort you're putting into all of this. No worries.

    For the record though, the problems you have been quoting so far, I didn't create. The tutorial's author wrote the content of:
    • phone_list_before.txt
    • phone_list_after.txt
    • grades_before.txt
    I'm responsible for writing "grades_assignment.txt". It may be that the tutorial's author wasn't quite as efficient at writing Python as he could have been, but I'm not in a position to know.

    Thanks again for all your help. :)
     
    Certifications: A+ and Network+
  6. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    I am genuinely speechless. I think he might need to look at this thread! :blink

    No problem. From what you've said about this tutorial's author, I'd look elsewhere to learn Python from. Their pace is a little slow and they're not letting you cover enough to perform the tasks at hand very well.

    There are 'tutorials' and tutorials. Get my drift? :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  7. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Which actually brings me to my next subject (which I was going to hold off on until after I finished the Cogliati tutorial...only 2 more chapters to go with one more exercise after the current one).

    The current tutorial (as far as I can tell) isn't written as well as it could be, but it does give me a "whirlwind tour" of the different aspects of programming with Python...at least enough to get my feet wet. Once finished, I plan to move on to something more formal and "polished". I have access to three texts on the subject:

    Dive into Python

    Learning Python

    Core Python Programming

    I've been leaning towards the "Core" book by Wesley Chun. The first two books are both marketed as good for teaching already experienced programmers the Python programming language. Chun's book seems to be the only one that can be readily used by someone without a lot of prior programming experience.

    Probably regardless of which book I use, I'll get a more organized presentation of the Python language, more concept material so I can understand "why" things work, and more feedback on exercises, since each book has a set of exercises to follow and an answer key with explanations in the appendix.

    I also snagged a copy of Goldwasser's and Letscher's Object-Oriented Programming in Python but thought I'd reserve that until after I made my way through one of the other Python "tomes".

    Options on this plan?
     
    Certifications: A+ and Network+
  8. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Well, when I was learning the language from a standing start I used Beginning Python: From Novice to Professional. I personally think that it is the best book out there as it takes you through a lot of Python at a pace that you can absorb, with very relevant information to tackle the next task. All I did was read the first couple of chapters then got by using it as a reference. In the later chapters it does tend to wind down on the specifics, but by then you are more than likely to have a good grasp to work things out for yourself.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  9. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    I read the reviews for this book and they tend to present the "Beginning Python" book as one good for people who *already know* another programming language. I guess the point I'm trying to get at is that I need a resource that will take me from the point of not knowing programming at all (except for the experience you're aware of) and using Python to introduce me to both programming in general and Python in particular. I can only assume (though I could be wrong) that Python wasn't your first programming language. True?
     
    Certifications: A+ and Network+
  10. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Python is my last programming language to date. I've endured about ten languages since I was a teen. :)

    The trouble with programming, as with any other subject, is that when you're getting to know it you have this initial 'brick wall' that you must patiently overcome; problems getting to understand the structure of the language, and applying the structure to solve problems. There is no book out there to take you from a standing start in programming, as it were - that is something that requires the guidance of a human tutor. Why a 'human tutor'? Because books assume what your potential weaknesses are in learning to program, whereas a tutor will be able to recognise specifically what your weaknesses are exactly and work with them. Also the books that start off too basic tend to remain that way, and to the novice programmer, if they've completed that basic text they assume that the are proficient programmers. In the real world of programming they are soon brought down to earth.

    As I always try to say, try not to write off a book on a few reviews, since everyones weaknesses are different. I would suggest that you visit the largest bookshop that you can find with a healthy selection of programming texts (you should know of a few given that you are an author :biggrin), find the Python section and read a page or two of each. That's exactly how I select my books and I'm yet to find a book that I didn't like when I took that approach.

    Like anything else you purchase, only you can make the decision after trying the product.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  11. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    True enough, however financial constraints require that I try to use as many of the resources at hand as I can, without dipping into my piggy bank, so to speak. A human tutor would be ideal, but again, time and money have to be factored in (I'm not even sure if Python is taught at the local uni or any other institution where I'd have access to a human being).

    Even if it's not ideal, I'll have to make due with what I've got at hand and do the best I can under current circumstances. I figure with time, study, and practice (and bugging you), I'll begin to pick up the basics. After that, we'll see how things go.

    Thanks again for your input and your patience. :)
     
    Certifications: A+ and Network+
  12. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Hi Trip

    Finally got round to it. Sorry again.

    Here is a more clean structure to the code sans file IO:

    Code:
    import os
    
    ValidMenuOptions = [1,2,3,4,5]
    
    number = {}
    
    def addDictKey(name, numb):
        '''
        Function to create unique
        dictionary key to store phone
        details.
        '''
        
        global number
        
        
        if number.has_key(name):
            print "Key already exists!"
        else:
            # We create the key...
            number[name] = numb
            
            
    def deleteDictKey(name):
        '''
        Deletes a dictionary
        entry only if it already
        exists.
        '''
        
        global number
        
        if not number.has_key(name):
            print "Key doesn't exist."
        else:
            del number[name]
            
            
    def listDictDetails():
        '''
        Iterates through dictionary
        items.
        '''
        
        global number
        
        for key in number.iteritems():
            print "Name: %s and Number: %s" % (key[0], key[1])
            
    
    def lookUpdetails(name):
        '''
        Retrieves details for 'name'
        if they exist.
        '''
        
        global number
        
        if not number.has_key(name):
            print "Key doesn't exist."
        else:
            print "Name: %s and Number: %s" % (name, key[name])   
            
    
    def printMenu():
        '''
        Print menu frondend.
        '''
        print
        print '1. Print Phone Numbers'
        print '2. Add a Phone Number'
        print '3. Remove a Phone Number'
        print '4. Lookup a Phone Number'
        print '5. Quit'
        print
       
        
    
    def run():
        
        menu_choice = 0
        
        
        while menu_choice != 5:
            while menu_choice not in ValidMenuOptions:
                printMenu()
                menu_choice = input("Type in a number (1-5):")
                
            if menu_choice == 1:
                listDictDetails()
                menu_choice = 0
                continue
            elif menu_choice == 2:
                name = raw_input("Name:")
                phone = raw_input("Number:")
                addDictKey(name, phone)
                menu_choice = 0
                continue
            elif menu_choice == 3:
                name = raw_input("Name:")
                deleteDictKey(name)
                menu_choice = 0
                continue
            elif menu_choice == 4:
                name = raw_input("Name:")
                lookUpdetails(name)
                menu_choice = 0
                continue
            else:
                print
                print "Exiting program."
            
    
    if __name__ == '__main__':
        run()
    
    Which is a clean and clear base to work from. Still a little fuzzy as to what you want fron the file IO - do you want that in addition to storing details in the dictionary?
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  13. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Thanks for getting back. Sorry, but I've been a tad occupied so far this weekend and haven't had the opportunity to really focus on this. Let me have a look and I'll post back when I've had a chance to devote some time to it.

    Thanks again. :)
     
    Certifications: A+ and Network+
  14. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    No problem, mate. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  15. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Hmmm. I think what we have here is a failure to communicate. I know that sometimes, I have a hard time expressing myself when discussing a programming language. I imagine it comes from a lack of formal education in such matters. The code you posted isn't actually, the program I'm trying to work on. First off, here is the basic program:
    Code:
    max_points = [25,25,50,25,100]
    assignments = ['hw ch 1','hw ch 2','quiz  ','hw ch 3','test']
    students = {'#Max':max_points}
    def print_menu():
        print "1. Add student"
        print "2. Remove student"
        print "3. Print grades"
        print "4. Record grade"
        print "5. Print Menu"
        print "6. Exit"
    def print_all_grades():
            print '\t',
            for i in range(len(assignments)):
                print assignments[i],'\t',
            print
            keys = students.keys()
            keys.sort()
            for x in keys:
                print x,'\t',
                grades = students[x]
                print_grades(grades)
    def print_grades(grades):
        for i in range(len(grades)):
            print grades[i],'\t\t',
        print
    
    print_menu()
    menu_choice = 0
    while menu_choice != 6:
        print
        menu_choice = input("Menu Choice (1-6):")
        if menu_choice == 1:
            name = raw_input("Student to add:")
            students[name] = [0]*len(max_points)
        elif menu_choice == 2:
            name = raw_input("Student to remove:")
            if students.has_key(name):
                del students[name]
            else:
                print "Student: ",name," not found"
        elif menu_choice == 3:
            print_all_grades()
        elif menu_choice == 4:
            print "Record Grade"
            name = raw_input("Student:")
            if students.has_key(name):
                grades = students[name]
                print "Type in the number of the grade to record"
                print "Type a 0 (zero) to exit"
                for i in range(len(assignments)):
                    print i+1,' ',assignments[i],'\t',
                print
                print_grades(grades)
                which = 1234
                while which != -1:
                    which = input("Change which Grade:")
                    which = which-1
                    if 0 <= which < len(grades):
                        grade = input("Grade:")
                        grades[which] = grade
                    elif which != -1:
                        print "Invalid Grade Number"
            else:
                print "Student not found"
        elif menu_choice != 6:
            print_menu()
    This program allows you to add and remove the names of "students", record and print their grades, print the menu and exit the program. The part here works fine in terms of those requirements.

    What the assignment is (and the part I'm having troubles with), is adding an I/O component that will let me write those grades to a separate text file and also import grades into the program from an external text file.

    The program you previously posted was the "example" is was supposed to work from (when the I/O portions were included). I'm unable to figure out how to adapt what that example presented to the current problem. I gave it a shot, but my best effort just pukes on me.

    Incidently, when I tried to run the program you posted, I hit a snag when I tried to lookup a phone number using option 4 (I'd previously added the phone number):
    Code:
    jmpyles@lamp:~/python$ python 15-1bexercise.py
    
    1. Print Phone Numbers
    2. Add a Phone Number
    3. Remove a Phone Number
    4. Lookup a Phone Number
    5. Quit
    
    Type in a number (1-5):1
    
    1. Print Phone Numbers
    2. Add a Phone Number
    3. Remove a Phone Number
    4. Lookup a Phone Number
    5. Quit
    
    Type in a number (1-5):2
    Name:Jim
    Number:555-5555
    
    1. Print Phone Numbers
    2. Add a Phone Number
    3. Remove a Phone Number
    4. Lookup a Phone Number
    5. Quit
    
    Type in a number (1-5):4
    Name:Jim
    Traceback (most recent call last):
      File "15-1bexercise.py", line 115, in ?
        run()
      File "15-1bexercise.py", line 106, in run
        lookUpdetails(name)
      File "15-1bexercise.py", line 62, in lookUpdetails
        print "Name: %s and Number: %s" % (name, key[name])
    NameError: global name 'key' is not defined
    jmpyles@lamp:~/python$
    I tried looking at the code, but I've got a headache and can make heads or tails of it right now (trying to cut back on coffee, and I think I'm going through withdrawls...which includes nasty headaches). :oops:
     
    Certifications: A+ and Network+
  16. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Hey Trip!

    Found what the problem was immediately, but will leave you to read the code to deduce what it is. ;)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  17. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    The problem with your code or mine? :blink
     
    Certifications: A+ and Network+
  18. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    The error message for the code that I posted. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  19. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Ok. Thanks. I'll let you know when I have it sorted.
     
    Certifications: A+ and Network+
  20. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    The part of the program defining how option 4 should lookup an existing name and number should be written as follows:
    Code:
    def lookUpdetails(name):
        '''
        Retrieves details for 'name'
        if they exist.
        '''
        
        global number
        
        if not number.has_key(name):
            print "Key doesn't exist."
        else:
            print "Name: &#37;s and Number: %s" % (name, [b]number[/b][name]) 
    In the original program, the word number which I have bolded is actually written as key. I think you just looked at "if not number.has_key(name)" and focused on "key(name)".

    I made the change and tested the program. It works now. I guess there's hope for me yet. :wink:
     
    Certifications: A+ and Network+

Share This Page

Loading...