[英]how to search in a file and read lines from there in python
我有一个巨大的文本文件,大约要读取100000行。 我对所有内容都不感兴趣。 我想搜索以“残基XXX”开头的行,并从那里读取接下来的三行。 我不想读取缓冲区列表中的整行。 有没有一种有效的方法来搜索该行并从那里开始阅读
f=open("result.txt",r)
lines = f.readlines()// NOT preferred
如果有一种方法可以在整个文件中搜索此行,而不是读取它们并进行迭代,则只需要输入一些内容。
您正在寻找类似的东西:
read_lines = None
for l in open("result.txt"):
if read_lines:
print l.encode('unicode_escape')
read_lines -= 1
if read_lines == 0:
break
if l.startswith('Residue ddG RotamerProbability'):
read_lines = 3
有更好的解决方案,但这是简单明了的。
除了读取数据外,实际上没有任何其他方法可以搜索文件。 读取数据的方式或多或少有效,因此,例如在C语言中执行数据可能比在Python中执行循环更快,但想必您想使用Python。
itertools
模块提供了两个与所需功能有关的功能: dropwhile
搜索具有特定属性的值,而islice
从可迭代islice
选择一个值范围:
import itertools
with open('result.txt') as infile:
def predicate(line):
return not line.startswith('Residue XXX')
result = list(itertools.islice(itertools.dropwhile(predicate, infile), 1, 4))
print result
with open("result.txt") as f:
# find line starting with Residue XXX
next(line for line in f if not line.startswith("Residue XXX"))
# get next three lines into a list (empty string for nonexistent lines)
results = [next(f, "").rstrip() for line in range(3)]
如果要将“ Residue XXX
行保留为results
列表的第一项,请执行以下操作:
with open("result.txt") as f:
# find line starting with Residue XXX
results = [next(line for line in f if not line.startswith("Residue XXX").rstrip()]
# add next three lines to the list (empty string for nonexistent lines)
results.extend(next(f, "").rstrip() for line in range(3))
文件对象是一个迭代器,如果在其他位置使用它,它将继续运行。 islice是从迭代器获取项目的便捷函数。 将所有内容放在一起,使用for循环查找起始位置,使用islice获得其余位置。
我不确定您是要在列表中包含匹配的行还是要对行尾进行处理,因此我决定添加匹配的行以及接下来的3行,而不添加尾行。
from itertools import islice
with open('result.txt') as f:
for line in f:
if line.startswith("Residue XXX"):
my_list = [line.strip()]
my_list.extend(extra.strip() for extra in islice(f, 3))
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.