Reading multiple lines from an external file - Python

时间:2017-11-14 08:14:08

标签: python python-3.x

I need to sum certain lines from an external file to calculate the total number for those certain lines. Such as there are 31 days in January and I need to add lines 1-31 to calculate a number of defects for that month. I tried using readline and readlines but all I got was the error code: "TypeError: must be str, not int".

Here is my code (formatting is a little off down below):

def main():
    print('Hello, this program will calculate the number of defects')
    print('per month and defects per year and average defects per 
    month.')
    counter = 0
    keepGoing = 'x'

jan = feb = mar = apr = may = jun = jul = aug = sep = oct = nov = dec = 0
choice = userSelection()
infile = open('data.txt', 'r')
while keepGoing == 'x':
    if choice == 1:
        keepGoing = 'y'
        jan = infile.readline(1-31)
        jan += counter
        print('The number of defects in January were:')

        feb = infile.readline(32-59)
        feb += counter
        print('The number of defects in February were:')

        mar = infile.readline(60-90)
        mar += counter
        print('The number of defects in March were:')

        apr = infile.readline(91-120)
        apr += counter
        print('The number of defects in April were:')

        may = infile.readline(121-151)
        may += counter
        print('The number of defects in May were:')

        jun = infile.readline(152-181)
        jun += counter
        print('The number of defects in June were:')

        jul = infile.readline(182-212)
        jul += counter
        print('The number of defects in July were:')

        aug = infile.readline(213-243)
        aug += counter
        print('The number of defects in August were:')

        sep = infile.readline(244-273)
        sep += counter
        print('The number of defects in September were:')

        oct = infile.readline(274-304)
        oct += counter
        print('The number of defects in October were:')

        nov = infile.readline(305-334)
        nov += counter
        print('The number of defects in November were:')

        dec = infile.readline(335-365)
        dec += counter
        print('The number of defects in December were:')
        print('Program ending, have a nice day.')

1 个答案:

答案 0 :(得分:0)

while循环并不是必需的。

infile = open('filename.txt','r')

infile_list = infile.readlines()

jan = infile_list[0:31]
feb = infile_list[31:60]
.
.
.
.