gpt4 book ai didi

python从给定关键字的文件中删除一定数量的行

转载 作者:太空宇宙 更新时间:2023-11-04 02:51:49 26 4
gpt4 key购买 nike

我有一个文件,其中包含以下几行。 (注意新行)

blah blah blah

ID:name1:1bj409ju9
how are you

Im good 100
blah blah

ID:name2:987krjtu
not so good

too bad 900
blah blah

some words blah blah

如您所见,以“ID”开头的行有一个模式。我的尝试是搜索 ID:name[x] 并删除 5 行(包括空格)。例如,我想从文件中删除以下几行。

ID:name1:10.1.1.10
how are you

I'm good 100
blah blah

我尝试了下面的代码,但它只删除了匹配“somename1”的行

#!/usr/bin/python
import fileinput

filename = r"file.txt"
counter = -1
for linenum,line in enumerate(fileinput.FileInput(filename, inplace=1)):
if "name1" in line:
counter = linenum + 6
if linenum == counter:
line.strip()
else:
print line,

请注意,我想去掉“blah blah”和“ID:somename2:987krjtu”之间的新空行。

最佳答案

你可以试试:

def delete_lines(name, finput):
for line in finput:
if line.startswith('ID:') and line.contains(name):
# iterate finput five times
for i in range(5):
next(finput)
else:
# print the other lines
print(line)
# if you want to have the remaining lines in a variable you could also yield them
yield(line)

然后调用函数:

lines = list(delete_lines('name1', fileinput.FileInput(filename, inplace=1)))

lines 将包含所有未删除的行。

请注意,同样的方法也适用于打开的文件描述符:

with open(filename, 'rt') as finput:
delete_lines('name1', finput)

或使用内存行列表(如果您不关心将整个文件加载到内存中):

with open(filename, 'rt') as finput:
lines = finput.readlines()
delete_lines('name1', finput)

关于python从给定关键字的文件中删除一定数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43635464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com