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:
JavaScript
x
10
10
1
element = element1
2
attribute1 = value1last
3
attribute2 = value2
4
attribute3 = value3
5
6
element =element2
7
attribute1 = value1last
8
attribute2 = value2
9
attribute3 = value3
10
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:
JavaScript
1
10
10
1
element = element1
2
attribute2 = value2
3
attribute3 = value3
4
attribute1 = value1last
5
6
element =element2
7
attribute2 = value2
8
attribute3 = value3
9
attribute1 = value1last
10
Appreciate any help on this.
Advertisement
Answer
Try this:
JavaScript
1
22
22
1
with open('input.txt', 'r') as f:
2
data = f.read().splitlines()
3
#print(data)
4
5
sep_lists = [[]]
6
for i in data:
7
if not i:
8
sep_lists.append([])
9
else:
10
sep_lists[-1].append(i)
11
12
#print(sep_lists)
13
for lists in sep_lists:
14
for idx, elem in enumerate(lists):
15
if 'last' in elem:
16
last = idx
17
lists.append(lists.pop(last))
18
19
with open('output.txt', 'w') as f:
20
for lists in sep_lists:
21
f.write('n'.join(lists) + 'nn')
22