1

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
5
  • Have you tried typecasting as an int (i.e. count = int(count + 1))? Commented Jul 1, 2016 at 16:26
  • Also, can you post more numbers in the series it produces, that give a little more information about what is generating the error. Commented Jul 1, 2016 at 16:28
  • Also, is your main goal to simply output a file with every 1000th data point from input. That could be written much simpler, and you may not even need count at all. Commented Jul 1, 2016 at 16:31
  • I tried count = int(count + 1)) and it doesn't work. I will add more output. Yeah, my goal is to output every 1000th data. Could you please let me know if there are some simpler ways? Commented Jul 1, 2016 at 16:34
  • Slice notation is still simpler data[::1000]. Commented Jul 1, 2016 at 16:54

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.