Issues formatting a new file in python

By : sourpet
Source: Stackoverflow.com
Question!

So I am pretty new to python ( and coding in general ) and I could use some serious help finding the problem in my code. Basically, I am opening a file that contains any number of students name followed 4 test scores. So Something like this:

John
78.0
80.0
69.0
98.0
Bob
40.0
78.0
77.0
89.0
etc

My program is suppose to then read said file and out put to the shell:

  John: 78.0 80.0 69.0 98.0 Average: 81.25
  Bob: 40.0 78.0 77.0 89.0 Average: 71.0

And finally it should save the names and averages to a new file like,

  John,81.25
  Bob, 71.0

However my program prints this to the screen:

Mary
 :76.0 89.0 82.0 100.0 Average: 86.75
Joey
 :91.0 81.0 83.0 95.0 Average: 87.5
Sally
 :92.0 93.0 90.0 97.0 Average: 93.0

And is saving files like this:

  Mary
  86.75Joey
  87.5Sally
  93.0

Can anyone help with either of these issues? Its a school assignment so just help identifying my bad coding would be sufficient.

Here is my mess of a code:

Create file containing students scores

scoresa = open('project3-scoresa.txt','w')
scoresa.write("Mary\n76\n89\n82\n100\nJoey\n91\n81\n83\n95\nSally\n92\n93\n90\n97")
scoresa.close()



def main():
    averages = open("averages.csv","w")
    file = input("Please enter the scores filename:")
    try:
        scores = open(file,'r')
        print("File",file,"has been opened")
    except IOError:
        print("File",file,"could not be opened.")
    scores = open(file,'r')
    i = 0
    for line in scores:
        if i%5 == 0:
            name = line
            print(name.strip("/n"),":", end="")
            j = 1
            total = 0
        else:
            score = float(line)
            print(score, end=" ")
            total += score
            ave = total/j
            if j == 4:
                print("Average:",ave)
                Avestring = (name + str(ave))
                averages.write(Avestring)
            j += 1
        i += 1
    scores.close()
    averages.close()
    average = open("averages.csv","r")
    for line in average:
        print(line.strip("\n"))
main()
By : sourpet


Answers

You have a typo in this line:

print(name.strip("/n"),":", end="")

i.e. you should have \n (the escape sequence indicating a new line character), not /n

This means that the newline character is not removed from the name when printing, which is why you have output like this:

Mary
 :76.0 89.0 82.0 100.0 Average: 86.75

rather than this:

Mary:76.0 89.0 82.0 100.0 Average: 86.75

(note you also need to add a space after the : to get your target output)

Note that even if you had used name.strip('\n') (i.e. without the typo), that you would still see the second problem when writing to file. Calling strip() on name doesn't alter the value of name itself, so the newline character is still in name when you do:

Avestring = (name   str(ave))
averages.write(Avestring)

To update the value of name you would do:

name = name.split('\n')

which takes the old value of name, calls split() on it and stores the returned result back into name.

However, in this case, you could simply do:

name = line.split('\n')

since you never need the name with the newline character included, so may as well remove it straight away.

By : E. Gordon


You are very close. Try this.

def main():
    averages = open("averages.csv","w")
    file = input("Please enter the scores filename:")
    try:
        scores = open(file,'r')
        print("File",file,"has been opened")
    except IOError:
        print("File",file,"could not be opened.")
    scores = open(file,'r')
    i = 0
    for line in scores:
        if i%5 == 0:
            name = line.strip("\n")
            print(name,":", end="")
            j = 1
            total = 0
        else:
            score = float(line)
            print(score, end=" ")
            total  = score
            ave = total/j
            if j == 4:
                print("Average:",ave)
                Avestring = (name   ","   str(ave)   "\n")
                averages.write(Avestring)
            j  = 1
        i  = 1
    scores.close()
    averages.close()
    average = open("averages.csv","r")
    for line in average:
        print(line.strip("\n"))
main()

Main changes are:

name = line.strip("\n") # note the \n not /n
print(name,":", end="")

Avestring = (name   ","   str(ave)   "\n") # note the comma and line break.
By : Dan-Dev


Your first problem can be solved by replacing "/n" by "\n" in the line no 20:

 print(name.strip("/n"),":", end="")

and this will turn to :

 print(name.strip("\n"),":", end="")

And the other changes that i made were in line no : 19 and 30 . I first sripped the string for the new line character . The new line of code will be .

name = line.strip("\n")
Avestring = (name  ","  str(ave)  "\n")
By : Atif Imam


This video can help you solving your question :)
By: admin