Skip to main content
 首页 » 编程设计

python之如何删除用于 Pylab 绘图的日志文件中的第一行

2025年05月04日8lvdongjie

我有一个程序,将电压与时间放在一个文件“logfile.txt”中。后来日志文件用于在 Pylab 中绘制图表。该程序工作正常,除了日志文件中的第一行需要在打印之前删除。我不知道为什么,但第一行包含上次测试的最后一个电压,即使在每次新测试开始之前日志文件显示为空。例如,这里是典型的日志文件中的前 4 行:

     1379812114.42 2.056 
 
     1379812129.0 2.130 
 
     1379812129.22 2.252 
 
     1379812129.45 2.266 

如果我可以将第一行保留在日志文件之外,从而将第一行保留在 Pylab 绘图之外,我会很高兴。那个 2.056 来自以前的测试,不应该在那里。以下是程序中的相关行:

 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) 

请您参考如下方法:

除了写入新文件之外,您还可以使用 numpy 的功能使用 np.genfromtxt 跳过文件开头和结尾的行。 .具体来说,您正在寻找的参数包括:

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

由于您使用的是 pylab,因此无论如何您都将隐式使用 numpy。