Reputation: 561
I am working on a code that does a lot of weird things. One of those weird things is it generates a file called combined.glm
and the content of this file looks like this:
object line_space {
content;
content;
}
object line_conf {
content;
content;
}
#2 more line_conf objects
object line_ug {
content;
content;
}
#70 more line_ug
object nod_l {
content;
content;
}
#65 more nod_l
I want to move all the nod_l
sections above line_ug
section i.e., right after line_conf
section. The way I am trying to do is something like this:
...
noding=open("combined.glm",'r').readlines()
combined_order=open("combined_order.glm",'w')
for ko,comblineo in enumerate(noding):
if 'object line_space {' in comblineo:
combined_order.writelines(noding[ko:ko+5])
for kt,comblinet in enumerate(noding):
if 'object line_conf {' in comblinet:
combined_order.writelines(noding[kt:kt+5])
for kr,combliner in enumerate(noding):
if 'object nod_l {' in combliner:
combined_order.writelines(noding[kr:kr+5])
for kf,comblinef in enumerate(noding):
if 'object line_ug' in comblinef:
combined_order.writelines(noding[kf:kf+5])
...
But it is not working (in my head, this makes sense). I have about 28 nod_l
copied properly, then lot of null
characters and about 16 line_ug
then another nod_l
and breaks. I am not sure what is going on.
Upvotes: 1
Views: 55
Reputation: 27273
This is dirty, but it works.
import re
old = open("combined.glm").read()
space = re.compile("object line_space {.*?}",re.DOTALL + re.MULTILINE)
conf = re.compile("object line_conf {.*?}",re.DOTALL + re.MULTILINE)
ug = re.compile("object line_ug {.*?}",re.DOTALL + re.MULTILINE)
nod = re.compile("object nod_l {.*?}",re.DOTALL + re.MULTILINE)
all_space = space.findall(old)
all_conf = conf.findall(old)
all_ug = ug.findall(old)
all_nod = nod.findall(old)
with open("combined_order.glm","w") as f:
for thing in all_space:
f.write(thing + "\n\n")
for thing in all_conf:
f.write(thing + "\n\n")
for thing in all_nod:
f.write(thing + "\n\n")
for thing in all_ug:
f.write(thing + "\n\n")
Upvotes: 2