[英]How can I insert a new line of string in a specific position with python3
我的問題的難點在於“具體位置”。 我想編寫一個腳本,首先測試代碼(文件)中是否存在某些特定字符串,然后在所有其他包含的末尾包含一個 header 文件。 例如,如果我在這個文件中找到SomeString
,那么之后
#include <oldfile1.h>
#include "oldfile2.h"
插入#include "someheaderfile.h"
如果可能的話,我正在尋找一個優雅的解決方案。
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))
您閱讀了文件,檢查您的字符串是否在其中。 然后逐行閱讀以定位 header 區域的末尾,然后重新構建行列表,添加額外的 header。
然后通過加入新列表重寫您的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.