我需要对外部文件中的某些行进行求和,以计算这些特定行的总数。例如,一月份有31天,我需要添加行1-31来计算该月的缺陷数量。我尝试使用readline和readline,但得到的都是错误代码:"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.')发布于 2017-11-14 16:33:25
while循环实际上并不是必需的。
infile = open('filename.txt','r')
infile_list = infile.readlines()
jan = infile_list[0:31]
feb = infile_list[31:60]
.
.
.
.https://stackoverflow.com/questions/47280683
复制相似问题