-1

I'm taking the median and mean of a list and then trying to print those numbers to an output text file. The only problem is every time I run the current code only one line is written in the file.

def mean(appleList):
    meanSum = 0
    for i in appleList:
        meanSum += int(i)
    myMean = round(meanSum/len(appleList), 2)
    outputFile = open('C:\\Users\\me1234\\OneDrive\\Desktop\\Code\\Output1', 'w')
    outputStr1 = ("The mean numbers of apples eaten is " + str(myMean))
    outputFile.write(outputStr1)
    outputFile.write("\n")
    outputFile.close()

def median(appleList):
    appleList.sort()
    if len(appleList)%2 != 0:
        num1 = int((len(appleList)+1)/2-1)
        myMedian = appleList[num1]
    else:
        num1 = len(appleList)/2-1
        num2 = len(appleList)/2
        myMedian = ((appleList[num1])+(appleList[num2]))/2
    outputFile = open('C:\\Users\\me1234\\OneDrive\\Desktop\\Code\\Output1', 'w')
    outputStr2 = ("The median numbers of apples eaten is " + str(myMedian))
    outputFile.write(outputStr2)
    outputFile.write("\n")
    outputFile.close()

The only thing in the output file is: "The median numbers of apples is 5", but I need both the mean and median results

  • 1
    Please read [ask] and [mre] and show a *complete* example. Right now, there is nothing that would cause either `mean` or `median` to run, so there is no way to diagnose or reproduce the problem as described. – Karl Knechtel Oct 15 '22 at 02:25

1 Answers1

0

You are rewriting the file. So, for while writing the median use this line

outputFile = open('C:\\Users\\me1234\\OneDrive\\Desktop\\Code\\Output1', 'a')
                                                          # changed here  ^
Rahul K P
  • 15,740
  • 4
  • 35
  • 52