python文件读取循环

2024-05-23 14:16:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输入

asd
ear
hello
hello
hello
rea
ear
world
world
rea
zxczxc

代码

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)

输出

ear
hello
hello
hello
rea

5
ear
hello
hello
hello
rea
ear
world
world
rea

9

预期产量

ear
hello
hello
hello
rea

5
ear
world
world
rea

4

Tags: intxtfalsehelloworlddataifcheck
2条回答
  • 您需要重新初始化data
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 = ''

输出:

ear
hello
hello
hello
rea

5
ear
world
world
rea

9
  • 注意:这不会打印4。从输出来看,似乎您要打印数据的长度。在这方面你的逻辑是错误的
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 = ''

相关问题 更多 >