Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write to the same file from different functions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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  ^
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading