简体   繁体   中英

How can I insert a new line of string in a specific position with python3

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM