【发布时间】: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