Hello and welcome to CertForums.co.uk, here we host free active certification forums with links to the best free resources for Microsoft's MCSA MCSE MCDBA Cisco's CCNA CCDA and CCNP, and CompTIA's A+ Network+ i-NET+ and Security+ certifications in the UK. If you wish to post or use other advanced features you will need to register first. Registration is absolutely free and takes only a few minutes to complete so sign up today!

If you have any problems with the registration process or your account login, please contact support

Go Back   CertForums > Computing Support Forums > Programming & Scripting
Home Forums Register Search Today's Posts Mark Forums Read

Python File I/O Assignment headache

Post New ThreadReply
 
Thread Tools Display Modes
  #1  
Old 27-Mar-2008, 10:37 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
Python File I/O Assignment headache

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.
Attached Files
File Type: txt phone_list_before.txt (1.1 KB, 8 views)
File Type: txt phone_list_after.txt (2.3 KB, 6 views)
File Type: txt grades_before.txt (2.0 KB, 5 views)
File Type: txt grades_assignment.txt (2.6 KB, 4 views)


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #2  
Old 27-Mar-2008, 10:55 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
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?



Last edited by Mathematix : 27-Mar-2008 at 11:05 PM.
 
Reply With Quote
  #3  
Old 28-Mar-2008, 12:03 AM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
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).

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.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #4  
Old 28-Mar-2008, 01:11 AM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
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?



Last edited by Mathematix : 28-Mar-2008 at 01:12 AM.
 
Reply With Quote
  #5  
Old 28-Mar-2008, 01:43 AM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
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.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #6  
Old 28-Mar-2008, 11:55 AM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
Quote:
Originally Posted by tripwire45 View Post
For the record though, the problems you have been quoting so far, I didn't create. The tutorial's author wrote the content of:...
I am genuinely speechless. I think he might need to look at this thread!

Quote:
Originally Posted by tripwire45 View Post
Thanks again for all your help.
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?


 
Reply With Quote
  #7  
Old 28-Mar-2008, 01:17 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
Quote:
Originally Posted by Mathematix View Post
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?
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?


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #8  
Old 28-Mar-2008, 01:37 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
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.


 
Reply With Quote
  #9  
Old 28-Mar-2008, 01:49 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
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?


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #10  
Old 28-Mar-2008, 09:08 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
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 ), 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.


 
Reply With Quote
  #11  
Old 28-Mar-2008, 10:06 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
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.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #12  
Old 12-Apr-2008, 09:09 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
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?


 
Reply With Quote
  #13  
Old 13-Apr-2008, 01:44 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477
Points: 4044 tripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 pointstripwire45 has over 4000 points
Power: 184
None
Join Date: 29 Jun 2003
Location: Boise, ID, USA
Certifications: A+ and Network+
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.


You know, I wish my parents played Mozart when I slept because half the time I don't even know what the heck anyone's talking about!
 
Reply With Quote
  #14  
Old 13-Apr-2008, 02:39 PM
Mathematix's Avatar
Mathematix Mathematix is offline
Longterm Member
Posts: 839
Points: 1149 Mathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 pointsMathematix has over 1000 points
Power: 24
None
Join Date: 09 Mar 2006
Location: London
Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
WIP: Not doing certs. Computer geek.
No problem, mate.


 
Reply With Quote
  #15  
Old 13-Apr-2008, 06:45 PM
tripwire45's Avatar
tripwire45 tripwire45 is offline
Administrator
Posts: 13,477