Languages and Scripting

Python data reformat assistance

 
user557
Member

Python data reformat assistance

Hello,

I wonder if someone can provide some Python assistance.  I have a simple requirement:

1. Print a line with UTC

2. Print any lines that follow, in this case those terminating with 1, 2 and 3

3. Prefix the lines (referenced in point 2) with the data segment enclosed in square brackets (referenced in point 1). 

4. Please refer to the 'datafile' and 'Desired output' in the box below 

5. My routine gives a partial result.

 

Thanks in advance

cat datafile
line...
line...
line...
[20/03/2020 10:38:456 UTC] Rest of the line
more information ...1
more information ...2
more information ...3
[21/03/2020 11:48:457 UTC] Rest of the line
more information ...5
more information ...6
more information ...7



$ cat reformat.py
#!/usr/bin/python3

outfile = '/tmp/datafile'
count = 0

with open(outfile, 'r') as fh:
    for line in fh:
        if line.find('UTC') != -1:  
            firstLine = line
            stub = line.split(']')
            newStub = stub[0]+']'
            print(firstLine, end='')


        elif line.find('more') != -1:
            while count <3:
                print(newStub,line, end='')
                count += 1
                break

$ python3 reformat.py
[20/03/2020 10:38:456 UTC] Rest of the line
[20/03/2020 10:38:456 UTC] more information ...1
[20/03/2020 10:38:456 UTC] more information ...2
[20/03/2020 10:38:456 UTC] more information ...3
[21/03/2020 11:48:457 UTC] Rest of the line


Desired output:

[20/03/2020 10:38:456 UTC] Rest of the line
[20/03/2020 10:38:456 UTC] more information ...1
[20/03/2020 10:38:456 UTC] more information ...2
[20/03/2020 10:38:456 UTC] more information ...3
[21/03/2020 11:48:457 UTC] Rest of the line
[21/03/2020 11:48:457 UTC] more information ...5
[21/03/2020 11:48:457 UTC] more information ...6
[21/03/2020 11:48:457 UTC] more information ...7