简体   繁体   中英

Match the last word and delete the entire line

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]

I believe with this you should be able to achieve what you want.

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

Here fname is the variable pointing to the file location.

You were almost there with your function. You were checking if : appears anywhere in the line, when you need to check if the line ends with it:

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

You could have also done if not line.strip()[:-1] == ':': , but endswith() is better suited for your use case.

Here is a compact way to do what you are doing above:

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)

The with statement creates a context and automatically closes files when the block ends.

To search if the last letter is : Do following

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

You can use a 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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