I am working on a file editing script that is able to find a certain section of the file based on some keywords, then replace a section below it with an alternative section. It is important to know that the files are formatted very strictly so variances should be little to none across files.
The files would look something like:
Z1 ; move to next (0)
Q6 ; comment1
X5 Y7 ; point
X6 Y9 ; point
X4 Y8 ; point
Q6 ; comment1
Z2 ; move to next (1)
Q6 ; comment1
X9 Y6 ; point
X4 Y2 ; point
X1 Y7 ; point
Q6 ; comment1
As of right now, my script is able to search the file and perform an action based on the comment after the ;, but I am unsure on how to delete what is there and replace it without iterating through the entire file multiple times.
It would look something like this:
stuff to add:
A1 B4 ; point
A7 B3 ; point
A1 B7 ; point
So the script would search looking for a case of 'Z1', then 'Q6' and if that happens, replace the 'X Y' section with the new 'A B' section. The edited version would then look like:
Z1 ; move to next (0)
Q6 ; comment1
A1 B4 ; point
A7 B3 ; point
A1 B7 ; point
Q6 ; comment1
Z2 ; move to next (1)
Q6 ; comment1
X9 Y6 ; point
X4 Y2 ; point
X1 Y7 ; point
Q6 ; comment1
My script so far is:
file_name = "/Users/path/to/file"
with open(file_name, 'r+') as f:
z_val = []
content = f.readlines()
for line in content:
coordinate_set = {}
if ';' in line:
if 'Z' in line:
try:
coord, comment = line.strip('\n').split(";")
for num in coord.split()[1:]:
if 'Z' in num:
z_val.append(num)
except:
pass
This works well to find the area with the 'Z1' and append the '1' value to a list, however I am unsure on how to make the section edit and replace. Some research into the topics makes me think that I may need to use enumerate and seek to work my way backwards up the section list as I delete each line I don't want, then, once it is at the bottom of the section, write in the new section.
Is there maybe a simpler or more efficient way to do this? Thank you in advance!!!