在python中增加整数

时间:2016-07-01 16:21:53

标签: python integer

我写了一个简单的函数来逐行读取文件,做一些计算并将结果存储在另一个文件中。但是,当我在函数中输出count时,而不是0,1,2,3;它变成了6.21263888889e-05,0.000141933611111等。我想知道是什么原因。

def CumulativePerSecond(input_file):
  # Record cumulative battery per second
  freq = 1000 # number of samples per second
  output_file = os.path.splitext(input_file)[0] + "_1s" + ".txt"
  output = open(output_file, 'a+')
  count = 0
  for line2 in fileinput.input(input_file):
    count = count + 1
    print count
    if count == freq:
        output.write(str(line2))
        count = 0
  output.close()

输出部分:

1.87317876361

1.87321708889

1.87325520083

1.87329356889

1.87333199389

1.87337076056

1.87340823167

1.87344365278

1.87347473167

1.87351439528

1.87354390806

1.87362505778

1 个答案:

答案 0 :(得分:1)

我不知道您的应用程序的细节,但我会将数据发送到列表,然后使用Python的切片表示法来选择每个第1000个数据点。

请尝试以下代码段。

data = range(100)
every_tenth = data[::10]

此外,如果您使用with关键字,则无需明确关闭文件。

with open(filename) as f:
    data = f.readlines()

以下是您的代码重写“Python” - 也就是说,它利用了Python为您提供的一些快捷方式。您可能需要稍微调整它以使其运行。我不确定你是如何处理你的文件的。

 def CumulativePerSecond(filename, freq=1000):
    data = []
    with open(filename) as input_file:
        data = input_file.readlines()

    output_file = os.path.splitext(filename)[0] + "_1s.txt"
    with open(out_filename, 'a+') as output:
        for line in data[::freq]:
            output.write(line)