How can I delete first line in a logfile used for a Pylab plot?

584 Views Asked by At

I have a program that takes voltages vs. time which is put into a file, 'logfile.txt'. Later the logfile is used to make a plot in Pylab. The program works fine except that the very first line in the logfile needs to be deleted before plotting. I don't know why, but the first line contains the last voltage from the previous test, even though the logfile shows empty before the start of each new test. For example here is typical of first 4 lines in logfile:

     1379812114.42 2.056

     1379812129.0 2.130

     1379812129.22 2.252

     1379812129.45 2.266

If I could just keep that first line out of the logfile and therefore out of the Pylab plot I'd be happy. That 2.056 is from a previous test and shouldn't be there. Here are the pertinent lines in the program:

 with open('logfile.txt', 'a') as f:
     while True:
        volts = adc.readADCDifferential01(4096, 8)
        sys.stdout.flush()
        if volts >=2.0:
            print >> f, time(), '{:.1f}'.format(volts)
            sleep(0.1)
2

There are 2 best solutions below

2
On

Thanks to an old post from SilentGhost:

lines = open('logfile.txt').readlines() 
open('newfile.txt', 'w').writelines(lines[1:-1])

This will create a new file from the original file, except the new file will not have the first or last lines of the original file. The new file can then be used to make the plot.

0
On

In addition to writing a new file, you can use numpy's capability to skip rows from the start and end of a file using np.genfromtxt. Specifically the arguments you are looking for include:

skip_header : int, optional

The numbers of lines to skip at the beginning of the file.

skip_footer : int, optional

The numbers of lines to skip at the end of the file

Since you are using pylab, you will be using numpy implicitly anyways.