【问题标题】:How to delete definite lines of a file which strats and ends with specific characters如何删除以特定字符结尾的文件的确定行
【发布时间】:2017-07-17 13:59:13
【问题描述】:

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

这是我的代码:

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 方法可以做到这一点,或者我必须拆分行,然后比较第一个和最后一个字符?

【问题讨论】:

    标签: python-3.x text-files text-extraction


    【解决方案1】:

    当您以这种方式阅读一行时,行尾有一个换行符或换行符/换行符,这通常对您来说是“不可见的”。您需要以某种方式处理它,否则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 来丢弃每行开头和结尾的空白。这是一种非常粗暴的做法。用起来会更好,

    line = line.rstrip()
    

    仅从字符串的右端去除空格。

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

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

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

    【讨论】:

    • 感谢您的解决方案!如果我想写其余的行并且不中断,我该怎么办!这意味着文件的其余部分应与输入文件相同!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多