erhan
erhan

Reputation: 307

multiply the numbers in a specific column by factor of 3

I want to multiply all the numbers in a specific column (z column in the following input file xyz.txt) by factor of 3 and output it in a in text file. When I run ./script.py xyz.txt > output.txt I get this error:

Traceback (most recent call last): File "./script.py", line 23, in sys.exit(main(sys.argv)) File "./script.py", line 18, in main result.append(z.split(' ')[2]*3) IndexError: list index out of range

Do you know how I can fix this error?

script.py:

#!/usr/bin/env python3

def main(argv):

    inputfile = open(argv[1])

    line = inputfile.readline()

    while line:
        print(line, end="")
        if line.startswith('[ xyz ]'):
            break
        line = inputfile.readline()

    result=[]
    for z in line:
        result.append(z.split(' ')[2]*3)
        print(z.rstrip(), '; modified')

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))

Input file xyz.txt:

[ xyz ]
;     x     y      z  
     1.5   3.5     6.3
     2.4   4.2     2.4
     3.2   8.9     8.9
     4.3   2.1     9.2
     5.4   6.3     3.5 

Requested output file output.txt:

[ xyz ]
;     x     y      z  
     1.5   3.5    18.9 ; modified
     2.4   4.2     7.2 ; modified
     3.2   8.9    26.7 ; modified
     4.3   2.1    27.6 ; modified
     5.4   6.3    10.5 ; modified

Upvotes: 0

Views: 81

Answers (1)

RyuCoder
RyuCoder

Reputation: 1822

import sys


def main(argv):

    inputfile = open(argv[1])

    line = inputfile.readline()

    result = []

    while line:

        # print(line, end="")
        # print(line)
        # print(len(line))
        # print(line.strip())
        # print(len(line.strip()))
        # print(line.strip().endswith("z"))
        # print("*" + line + "*")

        if line.strip().endswith("z"):
            result.append(line)
            line = inputfile.readline()
            continue


        # print()
        # print(line)
        # print("Z line")
        # print(line)
        # print(type(line))

        prev = line[:-5]
        z = line[-4:-1]

        # print(z)

        try:
            z = float(z)
        except ValueError:
            pass

        # print(type(z))
        # print()

        z = z * 3

        # print(z)

        z = str(z) + " ; modified"

        # print(z)

        output_line = prev + z

        # print(output_line)

        result.append(output_line)
        line = inputfile.readline()

    print(result)



if __name__ == "__main__":
    sys.exit(main(sys.argv))

Upvotes: 0

Related Questions