i'm writing a program that reads the lines of a file. each line has a name and and number separated by one space. i want to split the string but i only want the number because i'm using it in calculations. i've skimmed through the python docs and i'm still not sure how to do this. any help is apprecited, thank you!

Recommended Answers

All 7 Replies

Perhaps you should start with the output of

>>> help(str)
# PURPOSE: to calculate the running average of the ages of students in a class
#
# INPUT(S): the name of the file that contains the first name of the student
#           and their age separated by a space; the name of an output file
#
# OUTPUT(S): the running average will be written into the output file
#
# EXAMPLES:
#
################################################################################
import math
import string

def main():
    ifileName = raw_input('What file are the numbers in? ')
    ofileName = raw_input('What is the output file? ')
    inFile = open(ifileName, 'r')
    outFile = open(ofileName, 'w')
    total = 0.0
    count = 0
    line = inFile.readline()
    while line != "":
        name, num = string.split(line)
        total = total + eval(num)
        count = count + 1
        avg = total/count
        outFile.write('%d' %(avg))

main()

here's my code since it may seem that im fishing for some one to do it completely for me, i'm not. i didn't include the code because i thought i wouldn't need to for a simple question. the text file lines will look like this:
greg 18
matt 20
bob 26
ect.
i only want the numbers in the line. it might actually be a basic thing which is my problem with python, i always think that it's more complicated than it actually is. i just need a little help, is it a simple string.split and how do i get rid of everything except for the number.

Some comments. (Propably many times longer than the program you need to write)

## Your code with comments
import math
import string

def main():
    ifileName = raw_input('What file are the numbers in? ')
    ofileName = raw_input('What is the output file? ')
    inFile = open(ifileName, 'r')
    outFile = open(ofileName, 'w')
    total = 0.0
    count = 0
### Changes needed !!
    line = inFile.readline()  ## you read one line from the file
    while line != "": ## continue forever if line was not empty
        ## split return one value, study basic information about
        ## lists
        ## HINT: expression right starts: num = line.split
        ## for separating part of list from the rest of it
        ## see 'slice' from the python Help file 
        ## Help->Python Docs or F1 in IDLE

        name, num = string.split(line) 
                                    
        total = total + eval(num)
        count = count + 1
        avg = total/count
        outFile.write('%d' %(avg)) 

main()

After you post functioning, ugly code to this forum, I can show how to do it nicer and shorter, that is the way to use the forum.

Thanks for sending the try though, it is step to right direction.

Cheers,
Tony

>>data = "4 stringfour"
>>data = data.split()
>>print data
["4","stringfour"]
>>
>>int(data[0]) + 10 #use float() for decimals.
14

It appears that you did not test this code as you only read the first rec. Also you can use
for rec in inFile
instead of the while loop. And string.split() is deprecated, use line.split() instead.

line = inFile.readline()

   ##---------------------------------------------------------------
   ##   this is an infinite loop unless the 1st rec = ""
   ##---------------------------------------------------------------
    while line != "":
        name, num = string.split(line)
        total = total + eval(num)
        count = count + 1
        avg = total/count
        outFile.write('%d' %(avg))

And as I commented the same. Except that file has line=='' only if its line count is zero, as each line has character \n in the end. This moves the output to new line.

See here:

>>> line=open('t.py').readline()
>>> line
'## My style of coding\n'
>>>

My program has comment at first line and in the end before ' is end of line marker. It must be taken out same way from string at end as the first element can be removed from the list (if you don't learn special commands, don't worry those now.)

You can also based on your assignment only take the second element from line after splitting the line and return only second element on the line. However, I recommend to learn, how to say:'I want this list from the second element until the end of list'. This way you can have program, that adapts for lines with more than one number for each person.

Tony

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.