Search code examples
pythonarrayssortingreadlines

Storing lines into array and print line by line


Current code:

filepath = "C:/Bg_Log/KLBG04.txt"
with open(filepath) as fp:
    lines = fp.read().splitlines()
    with open(filepath, "w") as fp:
        for line in lines:
            print("KLBG04",line,line[18], file=fp)

output:

KLBG04 20/01/03 08:09:13 G0001 G

Require flexibility to move the columns around and also manipulate the date as shown below with array or list

KLBG04 03/01/20 G0001 G 08:09:13

Solution

  • You didn't provide sample data, but I think this may work:

    filepath = "C:/Bg_Log/KLBG04.txt"
    with open(filepath) as fp:
        lines = fp.read().splitlines()
        with open(filepath, "w") as fp:
            for line in lines:
                ln = "KLBG04 " + line + " " + line[18]  # current column order
                sp = ln.split()  # split at spaces
                dt = '/'.join(sp[1].split('/')[::-1])  # reverse date
                print(sp[0],dt,sp[3],sp[-1],sp[-2]) # new column order
                # print("KLBG04",line,line[18], file=fp)