匹配最后一个单词并删除整行

时间:2013-05-29 06:56:23

标签: python line

Input.txt文件

12626232 : Bookmarks 
1321121:
126262   

这里126262:可以是任何文字或数字,所以基本上会搜索最后一个单词是:(冒号)并删除整行

Output.txt文件

12626232 : Bookmarks 

我的代码:

def function_example():
    fn = 'input.txt'
    f = open(fn)
    output = []
    for line in f:
        if not ":" in line:
            output.append(line)
    f.close()
    f = open(fn, 'w')
    f.writelines(output)
    f.close()

问题:当我匹配时:它删除整行,但我只是想检查它是否存在于行尾,如果它是行尾,那么只删除整行。 任何建议将不胜感激。感谢。

我看到如下,但不知道如何在这里使用它

a = "abc here we go:"
print a[:-1]

4 个答案:

答案 0 :(得分:3)

我相信你应该能够实现你想要的目标。

with open(fname) as f:
    lines = f.readlines()
    for line in lines:
        if not line.strip().endswith(':'):
            print line

此处fname是指向文件位置的变量。

答案 1 :(得分:1)

你的功能几乎就在那里。您正在检查线路中的任何位置是否显示:,当您需要检查线路是否以此结尾时:

def function_example():
    fn = 'input.txt'
    f = open(fn)
    output = []
    for line in f:
        if not line.strip().endswith(":"):  # This is what you were missing
            output.append(line)
    f.close()
    f = open(fn, 'w')
    f.writelines(output)
    f.close()

您也可以完成if not line.strip()[:-1] == ':':,但endswith()更适合您的用例。

这是一种执行上述操作的简洁方法:

def function_example(infile, outfile, limiter=':'):
    ''' Filters all lines in :infile: that end in :limiter:
        and writes the remaining lines to :outfile: '''

    with open(infile) as in, open(outfile,'w') as out:
       for line in in:
         if not line.strip().endswith(limiter):
              out.write(line)

with statement创建一个上下文,并在块结束时自动关闭文件。

答案 2 :(得分:0)

要搜索最后一个字母是否:请执行以下操作

if line.strip().endswith(':'):
    ...Do Something...

答案 3 :(得分:0)

您可以使用regular expressio n

import re

#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"

with open(file_name) as _file:
    lines = _file.readlines()
    new_lines = [line for line in lines if regex.search(line.strip())]

with open(file_name, "w") as _file:
    _file.writelines(new_lines)
相关问题