2015-02-02 2 views
0

Я обрабатываю очень большой файл журнала для извлечения информации с использованием регулярного выражения Python. Тем не менее, я хотел бы обработать все строки только после того, как найду конкретную строку, которая в этом случае равна Starting time loop. Минимальная версия файла журнала выглядит следующим образом:Пропуск строк из текстового файла с использованием Python

Pstream initialized with: 
floatTransfer  : 0 
nProcsSimpleSum : 0 
commsType   : nonBlocking 
polling iterations : 0 
sigFpe : Enabling floating point exception trapping (FOAM_SIGFPE). 
fileModificationChecking : Monitoring run-time modified files using timeStampMaster 
allowSystemOperations : Disallowing user-supplied system call operations 

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 
Create time 

Create mesh for time = 0 


PIMPLE: Operating solver in PISO mode 


Reading g 

Reading relaxProperties 
Reading field p_rgh 

Reading field alpha1 

Reading field Urel 

Reading/calculating face flux field phi 

Reading transportProperties 

Selecting incompressible transport model Newtonian 
Selecting incompressible transport model Newtonian 
Selecting turbulence model type LESModel 
Selecting LES turbulence model Smagorinsky 
Selecting LES delta type vanDriest 
Selecting LES delta type cubeRootVol 
SmagorinskyCoeffs 
{ 
    ce    1.048; 
    ck    0.02; 
} 

Reading STFProperties 

Calculating field g.h 

time step continuity errors : sum local = 8.4072346e-06, global = -1.5271655e-21, cumulative = -1.5271655e-21 
GAMGPCG: Solving for pcorr, Initial residual = 1, Final residual = 4.7194845e-06, No Iterations 9 
GAMGPCG: Solving for pcorr, Initial residual = 0.13716381, Final residual = 2.9068099e-06, No Iterations 6 
time step continuity errors : sum local = 1.3456802e-10, global = -6.7890391e-13, cumulative = -6.7890392e-13 
Courant Number mean: 0.021611246 max: 0.39023401 
fieldAverage fieldAverage1: 
Starting averaging at time 0 


Starting time loop 

Courant Number mean: 0.02156811 max: 0.3894551 
Interface Courant Number mean: 0 max: 0 
deltaT = 0.00022522523 
Time = 0.000225225 

В настоящее время тестовый скрипт выглядит следующим образом:

logf = open(logName, 'r') 
p = logf.tell() 
logf.seek(0, 0) 
for l in logf: 
    if l.startswith('Starting time loop'): 
     print l 

Однако print l печатает все строки из файла журнала. Обратите внимание, что файл журнала открывается как logf

ответ

1

Не видя точного способа открытия файла журнала, трудно дать хорошую обратную связь по вашему маленькому сценарию.

Однако, здесь есть небольшой скрипт, который работает, как вы просили:

#!/usr/bin/env python 
logfile = 'logfile' 

start_line = 'Starting time loop' 
started = False 

with open(logfile) as f: 
    for l in f.readlines(): 
    if l.startswith(start_line): 
     started = True 
    if started: 
     print l.strip() 

Ниже приведен образец журнала:

$ cat logfile 
This is the first line 
This is the 2nd line 

This is the 3rd non-blank line 

Starting time loop and here we go 

Here are some more lines 
and some more 
yadda yadda yadda 
yadda yadda yadda 
yadda yadda yadda 
... 
And.. we're done 

Наконец, вот пробег небольшой журнала сценария:

$ ./log.py 
Starting time loop and here we go 

Here are some more lines 
and some more 
yadda yadda yadda 
yadda yadda yadda 
yadda yadda yadda 
... 
And.. we're done 
4

Хорошая вещь о итераторах python (к которым принадлежат файлы файлов) состоит в том, что они сохраняют состояние, поэтому, если у вас есть две петли for, вторая начинается, когда первая остановлена. Это приводит к следующему традиционной схеме:

for line in logf: 
    if <some condition> 
     break 

for line in logf: 
    process lines after that one 

Другой, более краткий способ сделать это itertools.dropwhile.

1

Код ниже читает по одной строке в то время. Когда конец файла достигнут, line - это пустая строка и перерывы цикла.

with open('your_file.txt', 'r') as opened_file: 

    while True: 
     line = opened_file.readline() 
     if not line: 
      break  

     else: 
      # Your code goes here 
      if line.startswith('Starting time loop'): 
       print line 

       break 

Было бы лучше, если вы используете with open() вместо этого, так как она закрывает файл автоматически, когда сделано.

Смежные вопросы