I am new to coding, trying to find a simple python code for re-arranging some lines. Lines have specific string to select. Those lines with this specific string need to be moved.
Original File content:
element = element1 attribute1 = value1last attribute2 = value2 attribute3 = value3 element =element2 attribute1 = value1last attribute2 = value2 attribute3 = value3
Note: the attribute line with “last” in it, this whole line should go to the end of each element’s attribute list.
New file format:
element = element1 attribute2 = value2 attribute3 = value3 attribute1 = value1last element =element2 attribute2 = value2 attribute3 = value3 attribute1 = value1last
Appreciate any help on this.
Advertisement
Answer
Try this:
with open('input.txt', 'r') as f:
    data = f.read().splitlines()
#print(data)
sep_lists = [[]]
for i in data:
    if not i:
        sep_lists.append([])
    else:
        sep_lists[-1].append(i)
#print(sep_lists)
for lists in sep_lists:
    for idx, elem in enumerate(lists):
        if 'last' in elem:
            last = idx
    lists.append(lists.pop(last))
with open('output.txt', 'w') as f:
    for lists in sep_lists:
        f.write('n'.join(lists) + 'nn')