简体   繁体   English

读取文件直到python中的特定行

[英]Read file until specific line in python

I have one text file.我有一个文本文件。 I am parsing some data using regex.我正在使用正则表达式解析一些数据。 So open the file and read it and the parse it.所以打开文件并读取它并解析它。 But I don't want to read and parse data after some specific line in that text file.但我不想在该文本文件中的某些特定行之后读取和解析数据。 For example例如

file start here..
some data...
SPECIFIC LINE
some data....

Now I don't want to read file after SPECIFIC LINE... Is there any way to stop reading when that line reaches?现在我不想在特定行之后读取文件......当该行到达时有没有办法停止读取?

This is pretty straight forward, you can terminate a loop early with a break statement.这非常简单,您可以使用break语句提前终止循环。

filename = 'somefile.txt'

with open(filename, 'r') as input:
   for line in input:
       if 'indicator' in line:
            break

Using with creates a compound statement that ensures that upon entering and leaving the scope of the with statement __enter__() and __exit__() will be called respectively.使用with创建一个复合语句,其确保在进入和离开的范围with语句__enter__()__exit__()将被分别称为。 For the purpose of file reading this will prevent any dangling filehandles.出于读取文件的目的,这将防止任何悬空的文件句柄。

The break statement tells the loop to terminate immediately. break语句告诉循环立即终止。

Use iter() 's sentinel parameter:使用iter()sentinel参数:

with open('test.txt') as f:
    for line in iter(lambda: f.readline().rstrip(), 'SPECIFIC LINE'):
        print(line)

output:输出:

file start here..
some data...

Reference: https://docs.python.org/2/library/functions.html#iter参考: https : //docs.python.org/2/library/functions.html#iter

Read only first n lines without loading the whole file:只读取前n而不加载整个文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM