在Python中删除指定行后n行
我想从一个文件中删除特定的几行。这些行总是在某个特定的注释行之后出现。说了这么多,下面是我现在的例子。
文件内容:--
randomstuff
randomstuff2
randomstuff3
# my comment
extrastuff
randomstuff2
extrastuff2
#some other comment
randomstuff4
所以,我想删除在 # my comment
之后的部分。也许在 r+
模式下有办法删除某一行?
这是我目前的代码
with open(file_name, 'a+') as f:
for line in f:
if line == my_comment_text:
f.seek(len(my_comment_text)*-1, 1) # move cursor back to beginning of line
counter = 4
if counter > 0:
del(line) # is there a way to do this?
我不太确定该怎么做。我该如何删除特定的一行呢?我看过这个可能的重复问题,但还是搞不清楚怎么做。答案建议你先读取文件,然后再重新写入。问题是,他们在写入时是检查特定的行。我不能完全这样做,而且我也不喜欢把整个文件的内容都存储在内存中的想法。对于大文件来说,这会占用很多内存(因为每一行都得存储,而不是逐行处理)。
有什么想法吗?
3 个回答
0
你只需要对你的代码做一个小改动,就可以很简单地把一个文件里的内容传输到另一个文件里。
with open(file_name, 'r') as f:
with open(second_file_name,'w') a t:
counter = 0
for line in f:
if line == my_comment_text:
counter = 3
elif: counter > 0
counter -= 1
else:
w.write(line)
0
我觉得@Ashwini的回答挺不错的。我之前也在研究这个解决方案,如果你愿意写一个新文件来保存过滤后的内容,像这样应该可以工作:
def rewriteByRemovingSomeLines(inputFile, outputFile):
unDesiredLines = []
count = 0
skipping = False
fhIn = open(inputFile, 'r')
line = fhIn.readline()
while(line):
if line.startswith('#I'):
unDesiredLines.append(count)
skipping = True
while (skipping):
line = fhIn.readline()
count = count + 1
if (line == '\n' or line.startswith('#')):
skipping=False
else:
unDesiredLines.append(count)
count = count + 1
line = fhIn.readline()
fhIn.close()
fhIn = open(inputFile, 'r')
count = 0
#Write the desired lines to a new file
fhOut = open(outputFile, 'w')
for line in fhIn:
if not (count in unDesiredLines):
fhOut.write(line)
count = count + 1
fhIn.close()
fhOut.close
1
你可以使用 fileinput
这个模块来实现这个功能,并且可以把文件打开为 inplace=True
模式,这样就可以直接在文件里进行修改了:
import fileinput
counter = 0
for line in fileinput.input('inp.txt', inplace=True):
if not counter:
if line.startswith('# my comment'):
counter = 4
else:
print line,
else:
counter -= 1
根据你的 评论 进行编辑 "或者直到找到空行为止":
import fileinput
ignore = False
for line in fileinput.input('inp.txt', inplace=True):
if not ignore:
if line.startswith('# my comment'):
ignore = True
else:
print line,
if ignore and line.isspace():
ignore = False