1

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.

H.C. Wu
  • 31
  • 5
  • 1
    Are you sure you are using Python? Python uses `import`, not `#include`. – Lyndon Gingerich Apr 16 '21 at 15:35
  • Would `SomeString` be in the original file or one of the imported files? – Lyndon Gingerich Apr 16 '21 at 15:36
  • The file I read is using C++, but I do not think this is important. The problem is that I do not know the number index of the line and I want to insert another include or import after that. – H.C. Wu Apr 16 '21 at 15:37
  • 1
    @themadpsychologist They're using Python to edit C code. – wjandrea Apr 16 '21 at 15:37
  • ```SomeString```would be in the original file. – H.C. Wu Apr 16 '21 at 15:38
  • the specification after which header it shoudl go is quite vague, but you can go dirty this way: `if 'SomeString' in file_content: file_content.replace("#include after_this_header", "#include after_this_header\n #include my_new_header")` – yedpodtrzitko Apr 16 '21 at 15:39
  • @yedpodtrzitko Yes, but the problem is I do not know what is ```after_this_header```, actually I need to search recursively every file in a folder. So, the ```after_this_header``` is not fixed and that is exactly the difficult part. – H.C. Wu Apr 16 '21 at 15:42
  • 1
    @yedpodtrzitko Please don't post answers in the comments. – wjandrea Apr 16 '21 at 15:43
  • I'm confused. Why wouldn't it work to read the file, check the beginning of each line to see whether it's an `#include`, and insert your `#include` before the first line that isn't? – Lyndon Gingerich Apr 16 '21 at 15:45
  • I've never tried this myself, but this question looks promising: [How do I write to the middle of a text file while reading its contents?](/q/16556944/4518341) Also this one if the line index is known: [Insert line at middle of file with Python?](/q/10507230/4518341) – wjandrea Apr 16 '21 at 15:46

1 Answers1

1
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.

Synthase
  • 5,849
  • 2
  • 12
  • 34