简体   繁体   English

如何使用 python3 在特定的 position 中插入新的字符串行

[英]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.我想编写一个脚本,首先测试代码(文件)中是否存在某些特定字符串,然后在所有其他包含的末尾包含一个 header 文件。 Eg If I find SomeString in this file, then after例如,如果我在这个文件中找到SomeString ,那么之后

#include <oldfile1.h>
#include "oldfile2.h"

insert #include "someheaderfile.h"插入#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.然后逐行阅读以定位 header 区域的末尾,然后重新构建行列表,添加额外的 header。

Then your rewrite your file by joining the new list.然后通过加入新列表重写您的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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