python - 如何过滤带有特定字符串的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
解决方案
你有一个很好的使用答案,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)
推荐阅读
- flutter - 在函数 Flutter 中定义时不显示 LinearPercentIndicator
- python - 为什么YOLOv3计算调整anchor box的offset值,而不是直接输出bounding box的维度?
- python - Anaconda 4.7.12 激活环境不起作用
- mysql - 合并连续相同的行
- spring - Spring Integration - 使用 Java 配置转换服务激活器
- excel - 引用工作簿和 For 循环的问题
- c++ - 为什么我的代码没有打印最大的数字?
- sharepoint - 谷歌 Colab - Sharepoint
- python - 如何在 django ManyToMany 管理员中搜索
- php - Magento 管理页面需要永远加载