Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中删除文件特定行之后的n行数_Python_File - Fatal编程技术网

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

在python中删除文件特定行之后的n行数,python,file,Python,File,我试图从文件中删除特定数量的行。这些行始终出现在特定注释行之后。不管怎么说,谈话是廉价的,这是我的一个例子 文件:-- 因此,我试图删除#我的评论之后的部分。也许有什么方法可以在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) # m

我试图从文件中删除特定数量的行。这些行始终出现在特定注释行之后。不管怎么说,谈话是廉价的,这是我的一个例子

文件:--

因此,我试图删除
#我的评论
之后的部分。也许有什么方法可以在
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?
不太清楚怎么做。如何删除特定行?我已经看过了,但也不太明白如何用那种方式来做。答案建议您先读取文件,然后再重新写入。这样做的问题是,他们在写入时正在检查特定的行。我不能完全做到这一点,而且我不喜欢将整个文件内容存储在内存中的想法。这将消耗一个大文件的大量内存(因为必须存储每一行,而不是一次存储一行)


有什么想法吗?

您可以对代码进行一些小的修改,并很容易地将内容从一个文件流到另一个文件

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)
您可以为此使用模块,并在
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
根据“或直到找到空行”编辑


我喜欢回答形式@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

删除
#我的评论
之后的所有行?要删除评论之后的所有行,还是仅在找到另一条评论之前?使用临时文件?将每行读入一个新文件。匹配后,停止写入。匹配后,再次开始写入。最后将其复制到一个新文件…@solarc仅复制该节。特定数量的行(如标题所示),而不是整个文件。或者,在找到一个空行之前,为什么我要将该行打印到stdout?@Humdinger当我们使用
inplace=True
时,标准输出实际上被重新定向到文件,因此这将很好。(查看文档了解更多详细信息:)哇。。那真的很酷。除此之外,读取的行还包含一个“/n”,因此打印前需要对该行进行条带化,否则此代码会在每次打印后创建额外的新行line@Humdinger这就是为什么我在打印后使用拖尾
。如果您使用的是Python3,那么请使用
print(line,end='')
。如果我希望它同时与2和3兼容,该怎么办?
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
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