ZigZagZebra
ZigZagZebra

Reputation: 1459

increment integer in python

I wrote a simple function to read a file line by line, do some calculation and store the results in another file. However, when I output count in my function, instead of 0, 1, 2, 3; it becomes 6.21263888889e-05, 0.000141933611111, etc. I'm wondering what is the reason.

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()

Parts of Output:

1.87317876361

1.87321708889

1.87325520083

1.87329356889

1.87333199389

1.87337076056

1.87340823167

1.87344365278

1.87347473167

1.87351439528

1.87354390806

1.87362505778

Upvotes: 1

Views: 1108

Answers (1)

Michael Molter
Michael Molter

Reputation: 1326

I don't know the specifics of your application, but I would send the data to a list, and then use Python's slice notation to select every 1000th data point.

Try the following snippet.

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

Also, you can eliminate the need to explicitly close files if you use the with keyword.

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

The following is your code re-written more 'Pythonically'--that is, it takes advantage of some of the shortcuts that Python offers you over C. You may have to fiddle with it a little to get it to run. I am not sure how you are handling your files.

 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)

Upvotes: 1

Related Questions