2

Input.txt File

12626232 : Bookmarks 
1321121:
126262   

Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line

Output.txt File

12626232 : Bookmarks 

My Code:

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()

Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line. Any suggestion will be appreciated. Thanks.

I saw as following but not sure how to use it in here

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

4 回答 4

3

我相信有了这个你应该能够实现你想要的。

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

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

于 2013-05-29T07:07:44.367 回答
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语句创建上下文并在块结束时自动关闭文件。

于 2013-05-29T07:12:15.287 回答
0

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

if line.strip().endswith(':'):
    ...Do Something...
于 2013-05-29T07:01:00.527 回答
0

您可以使用正则表达式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)
于 2013-05-29T10:46:44.837 回答