简体   繁体   English

在python中文件的特定行之后删除n行

[英]Deleting n number of lines after specific line of file in python

I am trying to remove a specific number of lines from a file. 我正在尝试从文件中删除特定数量的行。 These lines always occur after a specific comment line. 这些行总是出现在特定的注释行之后。 Anyways, talk is cheap, here is an example of what I have. 无论如何,谈话很便宜,这是我所拥有的例子。

FILE: -- 文件:-

randomstuff
randomstuff2
randomstuff3

# my comment
extrastuff
randomstuff2
extrastuff2

#some other comment
randomstuff4

So, I am trying to remove the section after # my comment . 因此,我试图在#my # my comment之后删除该部分。 Perhaps there is someway to delete a line in r+ mode? 也许有某种方式可以在r+模式下删除一行?

Here is what I have so far 这是我到目前为止的

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?

Not exactly sure how to do this. 不确定如何执行此操作。 How do I remove a specific line? 如何删除特定行? I have looked at this possible dup and can't quite figure out how to do it that way either. 我已经看过这种可能的重复 ,也无法完全弄清楚该怎么做。 The answer recommends you read the file, then you re-write it. 答案建议您阅读文件,然后重新编写。 The problem with this is they are checking for a specific line when they write. 问题是他们在写时正在检查特定行。 I cant do that exactly, plus I dont like the idea of storing the entire files contents in memory. 我不能完全做到这一点,而且我不喜欢将整个文件内容存储在内存中的想法。 That would eat up a lot of memory with a large file (since every line has to be stored, rather than one at a time). 这将占用一个大文件的大量内存(因为必须存储每一行​​,而不是一次存储一行)。

Any ideas? 有任何想法吗?

You can make a small modification to your code and stream the content from one file to the other very easily. 您可以对代码进行少量修改,然后非常轻松地将内容从一个文件传输到另一个文件。

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)

You can use the fileinput module for this and open the file in inplace=True mode to allow in-place modification: 您可以为此使用fileinput模块,并以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

Edit per your comment "Or until a blank line is found": 按照您的编辑 评论 “或者直到一个空行发现”:

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

I like the answer form @Ashwini. 我喜欢答案形式@Ashwini。 I was working on the solution also and something like this should work if you are OK to write a new file with filtered lines: 我也在研究解决方案,如果您可以编写包含过滤行的新文件,则类似的内容应该可以工作:

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

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

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