【发布时间】:2018-04-30 22:22:27
【问题描述】:
我有一个文件 (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
file2.txt:
p1 4.252613E+01
p3 4.272667E+01
p10 4.258108E+01
【问题讨论】:
-
为什么包含
p10?它似乎不在您的indref列表中 -
在 'p1' 之后添加空格或制表符 '\t'(取决于文件中的内容)或使用正则表达式
-
@chrisz 这就是问题所在。