Search code examples
pythontext

Change specific column values from a text file using Python


I have a text file as following:

1  1  2  1  1e8
2  1  2  3  1e5
3  2  3  2  2000
4  2  5  6  1000
5  2  4  3  1e4
6  3  6  4  5000
7  3  5  2  2000
8  3  2  3  5000
9  3  4  5  1e9
10 3  2  3  1e6

My question is that how can I change one column(for example divide all the data from the last column to 900) and save the whole data in a new file? Thanks in advance


Solution

  • You can use numpy library. The code below should do it.

    import numpy as np
    
    # assume the data is in.txt file
    dat = np.loadtxt('in.txt')
    
    # -1 means the last column
    dat[:, -1] = dat[:, -1]/900
    
    # write the result to the out.txt file
    # fmt is the format while writing to the file
    # %.2f means that it will save it to the 2 digits precision
    np.savetxt('out.txt', dat, fmt='%.2f')