首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从外部文件读取多行- Python

从外部文件读取多行- Python
EN

Stack Overflow用户
提问于 2017-11-14 16:14:08
回答 1查看 54关注 0票数 0

我需要对外部文件中的某些行进行求和,以计算这些特定行的总数。例如,一月份有31天,我需要添加行1-31来计算该月的缺陷数量。我尝试使用readline和readline,但得到的都是错误代码:"TypeError:必须是str,而不是int“。

这是我的代码(下面的格式化有点小问题):

代码语言:javascript
复制
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.')
EN

回答 1

Stack Overflow用户

发布于 2017-11-14 16:33:25

while循环实际上并不是必需的。

代码语言:javascript
复制
infile = open('filename.txt','r')

infile_list = infile.readlines()

jan = infile_list[0:31]
feb = infile_list[31:60]
.
.
.
.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47280683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档