[英]python file reading loop issue
尝试从 txt 文件中获取数据时遇到问题。 解决方案肯定会很简单,但无论如何我认为我需要你的帮助。 现在它像'123 123456'那样打印,但我想像'123 456'一样打印它,有什么想法吗?
输入
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)
OUTPUT
ear
hello
hello
hello
rea
5
ear
hello
hello
hello
rea
ear
world
world
rea
9
预期 OUTPUT
ear
hello
hello
hello
rea
5
ear
world
world
rea
4
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 = ''
Output:
ear
hello
hello
hello
rea
5
ear
world
world
rea
9
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 = ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.