Search code examples
text-filesfile-writing

Writing a text file in new format


I have a text file like this:

   1 0.1278000E-01  0.000000      0.000000         
 259 0.1172645E-01-0.5057909E-02  0.000000         
 260 0.7262609E-02-0.1052830E-01  0.000000

It has 4 columns and 3 rows. The numbers in the last column are always zero. If the number in the third column is not zero (row 2,3) this number is attached to the number in the second column. I want to add something to this file and change its format to:

Point(1) = {0.1174800E-01, 0, 0};

Point(259) = {0.1172645E-01, -0.5057909E-02, 0};

Point(260) = {0.7262609E-02, -0.1052830E-01, 0};

Does anybody know how I can do it?

Thanks!


Solution

  • A solution to this problem in Python 3.6:

    lines = [line.rstrip('\n') for line in open('input.txt')]
    output = open('output.txt', 'w')
    
    for line in lines:
        line = line.split()
        if len(line) == 3:
             line[1], line[2] = line[1][:line[1].find("E") + 4], 
                                        line[1][line[1].find("E") + 4:]
        output.write('Point({}) = {{{}, {}, 0}};\n'.format(line[0], line[1], line[2] 
                                                            if float(line[2]) != 0 else '0'))
    
    output.close()
    

    EDIT: It's a bit hard coded now that the values are not separated by spaces, but it works fine. I think you could improve it with regex, I'll take a look.