Reputation: 31
I have a file looks like this:
(...)
- src: git+[server]
name: main
version: master
- src: git+[server]
name: sec
version: master
- src: git+[server]
name: compiler
version: master
- src: git[server]
name: libs
version: master
- src: git[server]
name: crosscomp
version: master
(...)
and I only want to change the version after
name: main
and
name: sec
So my idea was to read the whole file line by line into an array and check if the line begins with the name: master or name: sec. (with startswith()
)
But how can I access the line after the finding?
Upvotes: 2
Views: 63
Reputation: 171
maseterIndex = [i for i, x in enumerate(array) if x == "name: master"]
secIndex = [i for i, x in enumerate(array) if x == "name: sec"]
mergedlist = maseterIndex + secIndex
for index in mergedlist:
#do something with next line
print array[index+1]
Upvotes: 0
Reputation: 149823
You can process the lines in pairs and update the next line whenever the you find a matching line. You'll need to overwrite the contents of the file with new lines at the end.
with open(filename, 'r+') as f:
lines = f.readlines()
for i in range(len(lines)-1):
if 'name: main' in lines[i] or 'name: sec' in lines[i]:
lines[i+1] = lines[i+1].replace('master', 'newversion')
f.seek(0)
f.truncate()
f.writelines(lines)
Upvotes: 3