I am writing code that reads sequential ascii files and makes changes in them.
So far, I have managed to read the files and replace the strings. for instance:
import os
import re
parent_folder_path = '.'
for eachFile in os.listdir(parent_folder_path):
if eachFile.endswith('.sos'):
newfilePath = parent_folder_path+'/'+eachFile
file = open(newfilePath, 'r')
sos = file.read()
file.close()
sos = sos.replace('...KOORDSYS -1', '...KOORDSYS 22')
file = open(newfilePath, 'w')
file.write(str(sos))
file.close()
But I wish to find a specific position (i.e. a string) and insert the following three strings after it.
.DEF
..DRIFTSMERKING T26
..SPENNING T16
The structure of the sequential ascii files I am working with look like this:
.HODE
..TEGNSETT ISO8859-1
..TRANSPAR
...KOORDSYS 22
...ORIGO-NØ 0 0
...ENHET 0.01
..OMRÅDE
...MIN-NØ 6593309 455619
...MAX-NØ 6729987 588458
..SOSI-VERSJON 4.0
..SOSI-NIVÅ 2
..DAT0 20130313
What I want to do is exactly this:
searchline = '..DATO'
lines = f.readlines()
i = lines.index(searchline)
lines.insert(i, '.DEF')
lines.insert(i+1, '..DRIFTSMERKING T26')
lines.insert(i+2, '..SPENNING T16')
You're close. Just use a for loop to iterate the input lines and apply both of your rules. This example adds the data but peeks to see whether the file has already been transformed first.
import os
parent_folder_path = '.'
canned_insert = [
'.DEF' + os.linesep,
'..DRIFTSMERKING T26' + os.linesep,
'..SPENNING T16' + os.linesep]
canned_insert_buf = ''.join(canned_insert)
for eachFile in os.listdir(parent_folder_path):
if eachFile.endswith('.sos'):
newfilePath = os.path.join(parent_folder_path, eachFile)
lines = open(newfilePath, 'r').readlines()
with open(newfilePath, 'w') as f:
for i, line in enumerate(lines):
if line.strip() == '...KOORDSYS -1':
f.write('...KOORDSYS 22' + os.linesep)
else:
f.write(line)
if line.startswith('..DATO') and lines[i+1:i+4] != canned_insert:
f.write(canned_insert_buf)