Reputation: 31
The difficulty of my problem lies in the "specific position". I want to write a script that first test if some specific string existed in the code (of a file), then I include a header file at the end of all the other includes.
E.g. If I find SomeString
in this file, then after
#include <oldfile1.h>
#include "oldfile2.h"
insert #include "someheaderfile.h"
I am looking for an elegant solution if possible.
Upvotes: 1
Views: 508
Reputation: 6090
with open(fname,'r') as f:
s = f.read()
if 'SomeString' in s:
sl = s.splitlines()
for i, x in enumerate(sl):
if x[0] != '#':
out = sl[:i] + ['#include "someheaderfile.h"'] + sl[i+1:]
break
with open(fname,'w') as f:
f.write('\n'.join(out))
You read your file, check if your string is in it. Then you read line by line to locate the end of the header region and you reconstruct your list of lines, adding your extra header.
Then your rewrite your file by joining the new list.
Upvotes: 1