简体   繁体   中英

How do I loop through certain parts of a text file in Python?

Currently, a Python beginner looking for some help. I'm reading from a text file with 365 lines of integers. Each integer is representative of a day of the year. Like this, but for 365 lines:

1102
9236
10643
2376
6815
10394
3055
3750
4181
5452
10745

I need to go through the whole file and separate the 365 days into each of the 12 months and take the average of the numbers of each month. For instance, the first 31 lines are January, take the average, print it, then continue from there...

At this point I have written code that goes through the whole file and gives a total for the year and an average per day, but am stuck on splitting the file into the separate months and taking individual averages. What do I do to achieve this?

Here's my current code:

import math

def stepCounter ():
    stepsFile = open("steps.txt", "r")
    stepsFile.readline()

    count = 0
    for line in stepsFile:
        steps = int(line)
        count = count + steps
        avg = count / 365
    print(count, "steps taken this year!")
    print("That's about", round(avg), "steps each day!")

  stepsFile.close()

stepCounter()

I hope this question was clear enough. Thanks for any help!

You'll have to have the number of days per month. Either use a fixed table, or you could ask the calendar module:

In [11]: months = [calendar.monthrange(2017, m)[1] for m in range(1, 13)]

In [12]: months
Out[12]: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

In case you decide to use a fixed table the only month of interest is February during leap years. You could just increment that if calendar.isleap() is True.

Given an open file of integer per row you could simply slice it suitably, map int() over the slices, and use statistics.mean() :

In [17]: from statistics import mean

In [18]: from itertools import islice

In [19]: [mean(map(int, islice(the_file, mdays))) for mdays in months]
Out[19]: [15, 44.5, 74, 104.5, 135, 165.5, 196, 227, 257.5, 288, 318.5, 349]

where the_file was simply

In [13]: from io import StringIO

In [14]: the_file = StringIO()

In [15]: the_file.writelines(map('{}\n'.format, range(365)))

In [16]: the_file.seek(0)
Out[16]: 0

First, you need a list with the quantity of days in each month:

month_len = [31, 28, 31,
             30, 31, 30,
             31, 31, 30,
             31, 30, 31]

Now write a loop to step through the months, with another inside to step through the days:

for month_num in range(12):
    # Start a new month

    for day_num in range(month_len[month_num]):
        #Process one day

Do remember that Python indexing starts at 0, so you'll have month_num running 0-11, and day_num running 0-30 at most.

Can you take it from there?


RESPONSE TO OP'S COMMENT

Okay, you're handicapped: lists are disallowed. Instead, try this:

for month_num in range(1, 12):
    month_len = 31
    if month_num = 2:
        month_len = 28
    elif month_num = 4 or
         month_num = 6 or
         month_num = 9 or
         month_num = 11:
        month_len = 30

    for day_num in range(month_len):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM