首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python文件读取循环问题

问python文件读取循环问题
EN

Stack Overflow用户
提问于 2019-09-27 18:14:54
回答 2查看 54关注 0票数 0

在尝试从txt文件中获取数据时,我遇到了一个问题。解决办法肯定很简单,但无论如何,我想我需要你的一点帮助。现在它打印的像'123 123456',但我想打印它像'123 456',有什么想法吗?

输入

代码语言:javascript
复制
asd
ear
hello
hello
hello
rea
ear
world
world
rea
zxczxc

代码

代码语言:javascript
复制
check = False
data = ''
start = 'ear'
end = 'rea'

with open('bear.txt', 'r') as rf:
    lines = rf.readlines()
    for i,x in enumerate(lines):
        if start in x:
            check = True
        if check:
            data += str(x)
        if end in x:
            check = False
            print(data)
            print(i)

输出

代码语言:javascript
复制
ear
hello
hello
hello
rea

5
ear
hello
hello
hello
rea
ear
world
world
rea

9

预期产出

代码语言:javascript
复制
ear
hello
hello
hello
rea

5
ear
world
world
rea

4
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-27 18:31:26

代码语言:javascript
复制
check = False
data = ''
start = 'ear'
end = 'rea'

with open('bear.txt', 'r') as rf:
    lines = rf.readlines()
    for x in lines:
        if start in x:
            check = True
        if check:
            data += str(x)
        if end in x:
            check = False
            print(data)

            # Count of data that split by `\n`
            # However, there is one extra `\n` so minus 1.
            print(len(data.split("\n")) - 1)

            # If it is not initialized, the contents will remain intact
            data = ''
票数 0
EN

Stack Overflow用户

发布于 2019-09-27 18:24:02

需要重新初始化data的

代码语言:javascript
复制
check = False
data = ''
start = 'ear'
end = 'rea'

with open('temp.txt', 'r') as rf:
    lines = rf.readlines()
    for i,x in enumerate(lines):
        if start in x:
            check = True
        if check:
            data += str(x)
        if end in x:
            check = False
            print(data)
            print(i)
            data = ''

输出:

代码语言:javascript
复制
ear
hello
hello
hello
rea

5
ear
world
world
rea

9

  • NOTE:--它不会打印4。从输出结果看,它看起来像是要打印数据的长度。对于这部分,您的逻辑是错误的。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58139629

复制
相关文章

相似问题

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