Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取文件直到指定行_Python_Regex_Python 2.7_File_File Read - Fatal编程技术网

在python中读取文件直到指定行

在python中读取文件直到指定行,python,regex,python-2.7,file,file-read,Python,Regex,Python 2.7,File,File Read,我有一个文本文件。我正在使用正则表达式解析一些数据。因此,打开文件,读取并解析它。但我不想在文本文件中某一行之后读取和解析数据。比如说 file start here.. some data... SPECIFIC LINE some data.... 现在我不想在特定行之后读取文件。。。 有没有办法在该行到达时停止读取?这很简单,您可以使用break语句提前终止循环 filename = 'somefile.txt' with open(filename, 'r') as input:

我有一个文本文件。我正在使用正则表达式解析一些数据。因此,打开文件,读取并解析它。但我不想在文本文件中某一行之后读取和解析数据。比如说

file start here..
some data...
SPECIFIC LINE
some data....
现在我不想在特定行之后读取文件。。。
有没有办法在该行到达时停止读取?

这很简单,您可以使用
break
语句提前终止循环

filename = 'somefile.txt'

with open(filename, 'r') as input:
   for line in input:
       if 'indicator' in line:
            break
使用创建一个复合语句,以确保在进入和离开带有
语句的
的范围时,分别调用enter和
\uuuuuuuuuu()
\uuuuuuuu()
。为了读取文件,这将防止任何悬空的文件句柄

语句告诉循环立即终止

使用
iter()
sentinel
参数:

以open('test.txt')作为f的
:
对于iter中的线路(lambda:f.readline().rstrip(),“特定线路”):
打印(行)
输出:

file start here..
some data...

参考:

先只读
n
,不加载整个文件:

n = 5
with open(r'C:\Temp\test.txt', encoding='utf8') as f:
    head = [next(f) for x in range(n)]

是的,但是在那之后您将如何处理该文件?使用
中断的
for
循环?这是相当标准的。。。你能告诉我们你的努力,这样我们就可以帮助你,而不仅仅是要求我们为你做这件事吗?