首页 > 解决方案 > 如何过滤带有特定字符串的txt文件

问题描述

我有一个文件(file1.txt),其中第一列包含字符串,我想在另一个文件(file2.txt)中过滤其字符串与列表'indref'完全对应的行(参见代码)。问题是生成的文件(参见简短示例)还附加了那些以我要附加的值“开始”的字符串。我只想附加特定的字符串('indref' 中的那些)。谢谢你。

import numpy as np

indref = ['p1', 'p3']

with open('file1.txt') as oldfile, open('file2.txt', 'w') as newfile:

    for line in oldfile:
        if any(x in line for x in indref):
            newfile.write(line)

file1.txt 示例

p1        4.252613E+01  
p2        4.245285E+01  
p3        4.272667E+01 
p4        4.255809E+01  
p5        4.284104E+01  
p6        4.292802E+01  
p7        4.295814E+01  
p8        4.286242E+01  
p9        4.286862E+01  
p10       4.258108E+01  

文件2.txt:

p1        4.252613E+01  
p3        4.272667E+01 
p10       4.258108E+01  

标签: pythonstringfilter

解决方案


你有一个很好的使用答案,split但它可以被精简到

indref = ['p1', 'p3']

with open('file1.txt') as oldfile, open('file2.txt', 'w') as newfile:
    newfile.writelines(line for line in oldfile if line.split()[0] in indref)

推荐阅读