0

I have a huge txt file with data by lines. There are some that are blank, some that start with a number (date) and by text. The structure repeats itself as shows in the example below.

I want to create a new file where all the lines start with the date, followed by the text lines separated by a comma.

I suppose I need two variables to store the lines that start with number and text and combine the text ones until the next number is found, but I don“t know how to to that.

Any help would be great! Thanks!

Example:

Input

22-05-16 20:35:20
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967
V: 0.50642
P:       0x1
Lev: 1483.64

22-05-16 21:30:00
ABC:D
UP:84.4,DN:84.3,Q=93
F: 35.7967 
V: 0.50642
P:       0x1
Lev: 1483.64

Output:

22-05-16 20:35:20, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 
22-05-16 21:30:00, ABC:D, UP:84.4,DN:84.3,Q=93,F: 35.7967,V: 0.50642,P:       0x1,Lev: 1483.64 

1 Answers1

1

You could accumulate all lines until you see a blank line and write the accumulated string once you encounter a blank -

with open('infile.txt', 'r') as to_read, open('outfile.txt', 'w') as to_write:
    acc_str = ''
    for line in to_read:
        if line.strip() == '':
            to_write.write(acc_str + '\n')
            acc_str = ''
        acc_str += line.strip() + ' '
    else:
        to_write.write(acc_str)

Output

 22-05-16 20:35:20 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 
 22-05-16 21:30:00 ABC:D UP:84.4,DN:84.3,Q=93 F: 35.7967 V: 0.50642 P:       0x1 Lev: 1483.64 
Mortz
  • 4,654
  • 1
  • 19
  • 35