0

I am trying to calculate various numbers (mean, median, etc.) from a csv dataset and then write this information into a txt file. For reference, my dataset is SAT scores, so the sample I have below is code for SAT reading scores. Right now I am trying to use an array, and have this:

    a=[1,2,3,4,5,6]
    b=[rmean, rmed, rmax, rmin, rsd, rvar]

    output=open("output.txt", "w")
    output.write("For the variable READ:\n The mean is")
    for i in range(len(a)):
        output.write(" %i %5.2f\n" % (a[i], b[i]))
    output.close()


I want my txt file to look something like:

For the variable READ, the mean is [value of rmean variable], the median is [value of rmed variable], etc.

How do I manipulate the array to do that, as opposed to the matrix view it's currently outputting? And additionally, is there any way to avoid having to use the numbers in array a or to avoid having them appear in my txt file output? Thank you!

2
  • Can you try to be more clear about exactly the issue? You say array, but you have two lists. You also mention a "matrix view", but what do you mean exactly? Commented Dec 2, 2017 at 6:37
  • Sorry about the terminology, very much a beginner here. I said matrix thinking mathematically to describe it, but the output is what you would expect, with two columns and 6 rows. Thomas helped me with a solution below, which might clarify the question if you were curious. Thanks! Commented Dec 2, 2017 at 6:44

2 Answers 2

1

Do I understand you correctly that you only want to print one line with all values and you have all values already calculated and saved as variables? In that case there is no need for a for loop

output.write("For the variable READ:\n The mean is {0}, the median is {1}, the max is {2}, etc".format(rmean, rmedian, rmax, ...))

of if you want to read from your list

output.write("For the variable READ:\n The mean is {0}, the median is {1}, the max is {2}, etc".format(b[0], b[1], b[2], ...))
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly it, thank you. So since the variables have already been defined, the array is completely unnecessary?
0

My solution would be this one:

with open("output.txt", "w") as f:
    f.write("For the variable READ:\n ")
    for i in range(len(a)):
        f.write("The %4s is %5.2f\n" %(b[i][1:], a[i]))

But if you modify your b as:

b = ['mean', 'median', 'max', 'min', 'sd', 'variance']


with open("output.txt", "w") as f:
    f.write("For the variable READ:\n ")
    for i in range(len(a)):
        f.write("The %-8s is %5.2f\n" %(b[i], a[i]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.