简体   繁体   中英

Skip a blank line when reading a file in python using readline

My program parses different types of log files and some of them have empty lines at the beginning of a file. Getting a variable for the first line is very important in this program. I've figured out how to make it skip over the blank lines but I haven't been able to make it treat the first line with text as the real first line. My code is as follows

 if first_line.find('Chain') != -1:
    first_time = int(searchforfirsttime.group(2)

My after that I need an else statement that makes first_line = the second line of the file. Thanks.

Edit:

The first few lines of the file I am reading is

(Blank Line)
CODE: 30;  Chain 1;  Time = 92473622;   PASSIVE:; 127; 127; 127; 127;   ACTIVE:; 127; 127; 127; 127; 127; 127; 127; 127; 127; 127;   CAPS:; 0; 0; 0; 0; 0; 0; 0; 0; 0;   DELAYS:;   0; 0; 0; 0;
CODE:31;  Chain1:;  Time = 92473765;  DCInputPower = -28.587273; DCOutputPower = -23.745722; DCCoeffs:  I:0; Q:0I:0; Q:0I:0; Q:0I:0;
lines = filter(None, (line.rstrip() for line in open(logfile)))

This gives you list of all non-empty lines of your file.

UPDATE:

If you're having memory contraints, then you can use itertools.ifilter which returns a generator instead of list - suggested by CristianCiupit

Anish Shah has a great answer if you can fit your file in memory (EDIT: and now he has a great answer for both cases). If you can't, you can always try a while loop to keep looping until you find a first line and assign first_time .

first_time = None
while first_time is None:
  first_line = file.readline()
  if first_line.find('Chain') != -1:
     first_time = int(searchforfirsttime.group(2))

I assume you're using readline() to get that first line.

This is one thing I like about Python, is the dynamic typing. first_time can be anything, really, so we can start with a value that int() will never return. That guarantees that we don't leave until it worked.

If you're parsing an ASCII text file, you should be able to do the following:

LogFilePathNameString = '/path/to/log/file/LogFileName.log';

FirstLineString = '';
FirstLineIndex = 0;

with open( LogFilePathNameString, 'r' ) as LogFileObject:

    LogFileObjectLineStringsList = LogFileObject.readlines();

    NumFileLines = len( LogFileObjectLineStringsList );

    for i in range( 0, NumFileLines, 1 ):

        CurrentLineString = LogFileObjectLineStringsList[ i ];

        if ( CurrentLine != '\n' ):

           FirstLineString = CurrentLineString;
           FirstLineIndex = i;
           break;

        #fi

    #rof

#hitw

print ( 'Found ' + str(FirstLineString) + ' on Line ' + str(FirstLineIndex) '.' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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