簡體   English   中英

從外部文件讀取多行-Python

[英]Reading multiple lines from an external file - Python

我需要對外部文件中的某些行求和,以計算這些行的總數。 例如一月份有31天,我需要添加1-31行來計算該月的缺陷數量。 我嘗試使用readline和readlines,但得到的只是錯誤代碼:“ TypeError:必須為str,而不是int”。

這是我的代碼(格式在下面有些偏離):

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.')

while循環並不是真正必要的。

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

infile_list = infile.readlines()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM