Search code examples
pythonpython-3.xchunks

How to loop over a whole file 4 lines at a time?


I have a bunch of loops for calculations that I want to perform. I am calculating the average value of 4 lines in a file. However, I want to loop this calculation of an entire file with hundreds of numbers.

i.e.

2
5
3
7
3
1
4
6
2
4
3
2
...

would give

4.25 
3.5
2.75 
...

Can someone recommend a solution?


Solution

  • Your problem appears to be a general programming problem, not really a Python problem. You have a problem, you understand what needs to happen, but are having trouble coming up with a program.

    Think about it in small steps. What do you really want to happen?

    1. you want to open a (text) file for reading
    2. you want to take the next four values from the file
    3. you want to compute their average
    4. you want to write that average to the screen
    5. if there's more left in the file, you want to get back to 2.
    6. otherwise, you're done

    You assume the file is all single numbers on a line, that's ok. You assume the file will have a multiple of 4 lines, also ok. But you should probably also think about what happens if that's not true.

    Which part is giving you trouble? Which one of these steps cannot be easily found in the Python documentation or other StackOverflow questions?

    Just remember to break down a task in small, simple steps that together solve the problem. Understand the problem before you start writing code.