首页 > 解决方案 > 每次调用函数时追加到下一行

问题描述

该函数Capture(filename)读取输出filename.txt并将必要的内容转储到Data.csv文件中。但是每次我调用 Capture 函数时,被转储的数据都会被重写在同一行中。

def Capture(filename):
    impedance = 0 
    losses = {} 
    frequencies = {} 
    Xtalk = {}
    rows = []
    with open(PostProcessingFolder + '\Output_' + filename +'_LOG.txt') as f:
        for l in f:
            if l.startswith('Impedance = '):
                v = l[12:-7] 
                impedance = float(v)
            if l.startswith('Xtalk'):
                m = f.next()
                n = f.next()
                a = m.find('Step response Next')
                b = m.find('mV', a)
                frequencies[l + "Step response Next"] = str(m[a+20:b].strip())                    
                c = n.find('Step response Fext peak')
                d = n.find('@', c)
                e = n.find('inches', d)
                g = n.find('mV', e)
                frequencies[l + "Step response Fext peak @" + str(n[d+1:e].strip()) + "inches"] = str(n[e+7:g].strip())
            if l.startswith('Loss per inch'): 
                start = l.find('@') 
                stop1 = l.find('GHz', start) 
                stop2 = l.find('dB', start)
                frequencies['filename'] = filename
                frequencies['impedance (Ohms)'] = impedance
                frequencies["Loss per inch @" + str(float(l[start+1:stop1].strip())) + "GHz"] = float(l[stop1+5:stop2].strip())
    rows.append(frequencies)
    print(rows)
    df = pd.DataFrame(rows)
    #df.append(df, ignore_index=True)
    df.to_csv('Data.csv')

有没有办法可以在每次调用此函数时将数据添加到下一个连续行?

标签: pythonpandas

解决方案


您需要rows.append在行上进行更多缩进:

虽然你有

rows = []
with open(PostProcessingFolder + '\Output_' + filename +'_LOG.txt') as f:
        for l in f:
            ...
rows.append(frequencies)

你需要:

rows = []
with open(PostProcessingFolder + '\Output_' + filename +'_LOG.txt') as f:
        for l in f:
            ...
            rows.append(frequencies)

推荐阅读