2015-02-02 5 views
0

파이썬 정규 표현식을 사용하여 정보를 추출하기 위해 매우 큰 로그 파일을 처리하고 있습니다. 그러나 특정 문자열 (이 경우 Starting time loop)을 찾은 후에 만 ​​모든 행을 처리하고 싶습니다. 파이썬을 사용하여 텍스트 파일의 라인을 건너 뛰기

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

파일 객체가 속하는 파이썬 반복자에 대한 좋은 점은 상태를 유지한다는 것입니다. 두 개의 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()을 사용하면 파일을 자동으로 닫을 수 있기 때문에 더 좋을 수도 있습니다.

관련 문제