[英]Delete everything until certain string or character in python
我需要读取一个文件并删除所有内容,直到出现某个字符串为止。 这很简单,我编写了代码,但是没有用。 它返回我文件的全部内容。
我的输入文件:
/****************************************************************
*
* Function Name: ab
* Input Parameter: cd
* output Parameter: ef
* Return Value: hi
*
****************************************************************/
#include "file_a.h"
#include "file_b.h"
static inline function(int a, int b){
...
...
...
...
}
我必须删除所有内容,直到:
static inline function(int a, int b){
这样该语句将成为新文件的第一行。
我的密码
TAG = 'static'
def delete_until(fileName,outfile):
tag_found = False
with open ('output.txt',"w") as out:
with open(fileName,'r') as f:
for line in f:
if not tag_found:
if line.strip() == TAG:
tag_found = True
else:
out.write(line)
if __name__ == '__main__':
fileName = 'myfile.txt'
outfile = 'output.txt'
delete_until(fileName,outfile)
新文件再次具有全部内容。 我做错了什么?
如果要分析代码文件,它们通常足够小以装入内存。 届时,只需执行一个string.find
调用即可。
with open(fileName,'r') as fin, open('output.txt',"w") as fout:
text = fin.read()
i = text.find('static')
if i > -1:
fout.write(text[i:])
写道:
static inline function(int a, int b){
...
...
...
...
}
到output.txt
。
如果有一个机会, static
评论中出现的实际之前static
功能,并假设代码文件你分析由理智的人写,你可以检查一个换行符前面加上关键字。 唯一的变化是在这里:
i = text.find('\nstatic')
if i > -1:
fout.write(text[i + 1:])
归功于JFF 。
使用sed
:
$ sed '1,/static inline function(int a, int b){/d' < your-file.c
由于此测试,您的代码失败:
if line.strip() == TAG:
您是通过以下方式定义TAG
的内容的:
TAG = 'static'
但是您刚刚读到的行是:
'static inline function(int a, int b){'
这意味着您不能仅使用==
运算符进行比较。 根据您的要求,更改TAG
的值以匹配要搜索的内容(这是最明智的选择,因为注释中也包含static
也可以匹配),或者更改查找该字符串的方式。
def delete_until(fileName,outfile):
tag_found = False
with open ('output.txt',"w") as out:
with open(fileName,'r') as f:
for line in f:
if not tag_found:
if TAG in line:
tag_found = True
if tag_found:
out.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.