Read a complete data file and round numbers to 2 decimal places and save it with the same format
Question: I am trying to learn python and I have the intention to make the a very big
data file smaller and later do some statistical Analysis with R. I need to
read the data file (see below):

    
    
    SCALAR
    ND    3
    ST  0
    TS        10.00
    0.0000
    0.0000
    0.0000
    SCALAR
    ND    3
    ST  0
    TS      3600.47
    255.1744
    255.0201
    255.2748
    SCALAR
    ND    3
    ST  0
    TS      7200.42
    255.5984
    255.4946
    255.7014
    

and find the numbers and round it in two digits after decimal, svae the
maximum number with the namber in front of TS. At the end save the data file
with the same format like following:

    
    
    SCALAR
    ND    3
    ST  0
    TS        10.00
    0.00
    0.00
    0.00
    SCALAR
    ND    3
    ST  0
    TS      3600.47
    255.17
    255.02
    255.27
    SCALAR
    ND    3
    ST  0
    TS**MAX**      7200.42
    255.60
    255.49
    255.70
    

I have written a code like this:

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    import pickle
    
    # Open file
    f = open('data.txt', 'r')
    thefile = open('output.txt', 'wb')
    # Read and ignore header lines
    header1 = f.readline()
    header2 = f.readline()
    header3 = f.readline()
    header4 = f.readline()
    data = []
    for line in f:
        line = line.strip()
        columns = line.split()
        source = {}
        source['WSP'] = columns[0]
        #source['timestep'] = float(columns[1])
        source['timestep'] = columns[1]
        data.append(source)
    
    f.close()
    

but the number in front of TS cannot be read. I wanted to round the numbers
but the float which I used does not work. After that I wanted to put it in a
loop Any suggestion, Do I write the code in a good way? I will be very
thankfull for the help.


Answer: Try `"%.2f" % float(columns[1])` to round to two decimal places. Note that it
gives you a string, not a float. I don't understand the rest of what you're
asking.

`>>> "%.2f" % 255.5984`  
`'255.60'`

