Search code examples
pythonpython-3.xfilefor-loopreadfile

How do I make it print the outputs on same line?


I am trying to open two files and collect information for the years 2010 to 2019 and report the mean and standard deviation of just the claims in that year

mean_file = open('data/mean.txt', 'r')
std_file = open('data/std.txt', 'r')
count = 2009

for line in std_file:
    std = float(line)
    for line in mean_file:
        mean = float(line)
    count += 1
    print('Year',count, 'Mean:', mean, 'Standard Deviation:', std)

mean_file.close()
std_file.close()

I have the code above. The output I got is

Year 2019 Mean: 217557.4 Standard Deviation: 82296.33
Year 2019 Mean: 217557.4 Standard Deviation: 77808.0
Year 2019 Mean: 217557.4 Standard Deviation: 66939.77
Year 2019 Mean: 217557.4 Standard Deviation: 65486.56
Year 2019 Mean: 217557.4 Standard Deviation: 59126.12
Year 2019 Mean: 217557.4 Standard Deviation: 58712.14
Year 2019 Mean: 217557.4 Standard Deviation: 55465.54
Year 2019 Mean: 217557.4 Standard Deviation: 44621.54
Year 2019 Mean: 217557.4 Standard Deviation: 47821.1
Year 2019 Mean: 217557.4 Standard Deviation: 43170.7

Each time I change the position of the indent, it gives a different answer. I want the mean and standard deviation to be printed on the same line simultaneously just like the output below. I want the output to be like below. How do I make it print exactly like the output below?

Year 2010 Mean: 455692.98 Standard Deviation: 82296.33
Year 2011 Mean: 409110.4 Standard Deviation: 77808.0
Year 2012 Mean: 372226.67 Standard Deviation: 66939.77
Year 2013 Mean: 341826.79 Standard Deviation: 65486.56
Year 2014 Mean: 306567.67 Standard Deviation: 59126.12
Year 2015 Mean: 276956.5 Standard Deviation: 58712.14
Year 2016 Mean: 263900.21 Standard Deviation: 55465.54
Year 2017 Mean: 243116.25 Standard Deviation: 44621.54
Year 2018 Mean: 220894.98 Standard Deviation: 47821.1
Year 2019 Mean: 217557.4 Standard Deviation: 43170.7

Solution

  • for sline, mline in zip(std_file, mean_file):
       std = float(line)
       mean = float(line)
       count = count+1
       print('Year',count, 'Mean:', mean, 'Std:', std)