Home > OS >  How to write to the same file from different functions
How to write to the same file from different functions

Time:10-15

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

CodePudding user response:

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  ^
  • Related