从循环中删除数据并保存到文件

时间:2018-01-02 19:26:52

标签: python-2.7 loops save

我有两个循环,每个循环有两个变量。 cutoff1cutoff2包含测量数据,BxTimeByTime包含0到300秒的时间数据(用于在matplotlib中设置比例)。我使用过这个循环:

Loop = zip(BxTime,cutoff1)
for tup in Loop:
    print (tup[0], tup[1])

Loop2 = zip(ByTime,cutoff2)
for tup in Loop2:
    print (tup[0], tup[1])

它在我的PyCharm环境中打印一个垂直的测量列表和它们出现的时间,首先是Loop,然后是Loop2。我的问题有点复杂,因为我需要:

  1. 将此循环保存到将垂直写入数据的文件中。第一列cutoff1第二列BxTime,第三列cutoff2第四列ByTime
  2. 其次,在步骤1之前或之后,我需要删除具体的测量值。有什么想法吗?
  3. 更新:

    def writeData(fileName, tups):
    
        '''takes a filename, creates the file blank (and deletes existing one)
        and a list of 2-tuples of numbers. writes any tuple to the file where
        the second value is > 100'''
    
        with open(fileName,"w") as f:
            for (BxTime,cutoff1) in tups:
                if cutoff1 <= 100:
                   continue  # goes to the nex tuple
                f.write(str(BxTime) + '\t' + str(cutoff1) + "\n" )`
    
    
    
    Loop = zip(BxTime,cutoff1)
    # for tup in Loop:
    #    print (tup[0], tup[1])
    
    Loop2 = zip(ByTime,cutoff2)
    # for tup in Loop2:
    #     print (tup[0], tup[1])
    
    writeData('filename1.csv', Loop)
    writeData('filename2.csv', Loop2)
    

    我使用过该代码,但是:

    1. 仍有测量值包含100.0
    2. 在保存到文件之前,我必须等到整个循环打印出来,如何避免?
    3. 有没有其他方法可以将其保存到文本文件而不是csv,后来以Excel格式打开?

1 个答案:

答案 0 :(得分:1)

def writeData(fileName, tups):

    '''takes a filename, creates the file blank (and deletes existing one)
    and a list of 2-tuples of numbers. writes any tuple to the file where
    the second value is >= 100'''

    with open(fileName,"w") as f:
        for (tim,dat) in tups:
            if dat < 100:
               continue  # goes to the nex tuple
            f.write(str(tim) + '\t' + str(dat) + "\n" ) # adapt to '\r\n' for windows

像这样使用:

writeData("kk.csv", [(1,101),(2,99),(3,200),(4,99.999)])         

输出:

1   101
3   200

应该使用您的压缩LoopLoop2(时间,数据)。

您可能需要在Windows上将行尾从'\n'更改为'\r\n'