如何删除以特定字符开头和结尾的文件的确定行

How to delete definite lines of a file which strats and ends with specific characters

我有一个包含很多行的测试文件。我想删除具有特定开始和结束字符的行。

这是我的代码:

with open('test.txt', 'r') as f, open('output.txt', 'w') as out: 
    for i, line in enumerate(f):
        if (line.startswith('E3T') and line.endswith('3')): 
           out.write(line)
        elif (line.startswith('E4Q') and line.endswith('3')): 
           out.write(line)
        elif (line.startswith('E4Q') and line.endswith('4')): 
           out.write(line)
        elif (line.startswith('E4Q') and line.endswith('3')): 
           out.write(line)
        elif line.startswith('BC'):
            break

这是我的 test.txt 文件

E3T 1 2 1 3 3
E3T 2 4 2 5 1
E3T 3 3 5 2 4
E3T 3326 2001 2008 1866 10
E4Q 3327 1869 2013 2011 1867 9
E4Q 3328 1867 2011 2012 1868 8
E4Q 3329 1870 2014 2013 1869 4
E3T 8542 4907 4908 4760 5
E3T 8543 4768 4909 4761 9
E3T 8544 4909 4763 4761 6
E3T 17203 9957 9964 10161 3
E3T 17204 9957 10161 9959 2
BC  1 "Zulauf: Temperatur" 12 0 1 "HYDRO_WT-2D"
BC_DEF 12 1 "Temperatur [°C]" 5 "Zeit [s]" "Temperatur [°C]" 

输出应该是这样的:

E3T 1 2 1 3 3
E3T 3 3 5 2 4
E4Q 3329 1870 2014 2013 1869 4
E3T 17203 9957 9964 10161 3

我认为,由于空格,它不起作用。有什么 pythonic 方法可以做到这一点,或者我必须拆分行然后比较第一个字符和最后一个字符?

当你以这种方式阅读一行时,在它的末尾有一个换行符或一个 new-line/line-feed 字符,对你来说通常是 'invisible'。您需要以某种方式处理它,否则 endswith 将处理它而不是您要处理的字符。然后,当你输出一行时,你需要把换行符放回去。

with open('test.txt', 'r') as f, open('output.txt', 'w') as out: 

    for i, line in enumerate(f):
        line = line.strip()
        if (line.startswith('E3T') and line.endswith('3')): 
           out.write(line+'\n')
        elif (line.startswith('E4Q') and line.endswith('3')): 
           out.write(line+'\n')
        elif (line.startswith('E4Q') and line.endswith('4')): 
           out.write(line+'\n')
        elif (line.startswith('E4Q') and line.endswith('3')): 
           out.write(line+'\n')
        elif line.startswith('BC'):
            break

在这种情况下,我使用 strip 丢弃每行开头和结尾的白色 space。这是一种非常粗暴的做法。最好用,

line = line.rstrip()

仅从字符串的右端去除白色 space。

编辑,回答评论中的问题:

用这些行替换上面的最后一行,

    out.write(line+'\n')
else:
    continue