Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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 写入文件时尝试跳过与正则表达式匹配的行,但新文件有额外的新行_Python_Regex_File_Writetofile - Fatal编程技术网

Python 写入文件时尝试跳过与正则表达式匹配的行,但新文件有额外的新行

Python 写入文件时尝试跳过与正则表达式匹配的行,但新文件有额外的新行,python,regex,file,writetofile,Python,Regex,File,Writetofile,这是我问的一个问题的副产品 我正在尝试设置一种方法,可以根据输入字典编辑文本文件。这就是我到目前为止所做的: info = {'#check here 1':{'action':'read'}, '#check here 2':{'action':'delete'}} search_pattern = re.compile(r'.*(#.+)') with open(input_file_name, "r") as old_file, open(output_file

这是我问的一个问题的副产品

我正在尝试设置一种方法,可以根据输入字典编辑文本文件。这就是我到目前为止所做的:

info = {'#check here 1':{'action':'read'}, '#check here 2':{'action':'delete'}}

search_pattern = re.compile(r'.*(#.+)')        

    with open(input_file_name, "r") as old_file, open(output_file_name, "w+") as new_file:
        lines = old_file.readlines()

        for line in lines:
            edit_point = search_pattern.search(line)
            if edit_point:
                result = edit_point.group(1)
                if result in info and info[result]["action"] == "insert":#insert new lines to file
                    print("insert information to file")
                    new_file.write("\n".join([str(n) for n in info[result]["new_lines"]]))
                    new_file.write(result)
                elif result in info and info[result]["action"] == "delete":#skip lines with delete action
                    print("found deletion point. skipping line")
                else:#write to file any line with a comment that is not in info
                    new_file.write(line)
            else:#write lines that do not match regex for (#.*)
                new_file.write(line)
基本上,当您提交字典时,程序将遍历文件,搜索注释。如果注释在字典中,它将检查相应的操作。如果操作是插入,则会将行写入文件。如果它是delete,它将跳过该行。任何没有注释的行都应写入新文件

我的问题是,当我从文件中删除一行时,似乎在它们原来所在的位置有额外的新行。例如,如果我有一个列表:

hello world

how are you #keep this
I'm fine #check here 2
whats up
我预计产出为:

hello world

how are you #keep this
whats up
但我在这里有一个空行:

hello world

how are you #check here 2

whats up

我怀疑这是我的最后一条else语句,它会将任何与edit_点不匹配的行写入文件,在本例中是新行。然而,我的理解是for循环应该一行接一行地进行,并简单地执行该行。有人能告诉我这里缺少什么吗?

您的代码、输入文本和输出文本不匹配。你的
info
字典没有
键#保留此键
键#删除此键
,因此它将始终为False并分支到else语句,在这种情况下,它应该只打印整个文件。我尝试了你的代码,文件未经修改就返回。你确定你发布的代码和你的一模一样吗?代码和我的一模一样。该文件唯一的区别是,我在这里输入了#delete,而不是#check here 2,以描述预期的行为。我已更新文件以反映这一点。您的代码、输入文本和输出文本不匹配。你的
info
字典没有
键#保留此键
键#删除此键
,因此它将始终为False并分支到else语句,在这种情况下,它应该只打印整个文件。我尝试了你的代码,文件未经修改就返回。你确定你发布的代码和你的一模一样吗?代码和我的一模一样。该文件唯一的区别是,我在这里输入了#delete,而不是#check here 2,以描述预期的行为。我已经更新了文件以反映这一点。