gpt4 book ai didi

python - 遍历字符串列表直到 string == newline

转载 作者:行者123 更新时间:2023-11-28 22:11:30 28 4
gpt4 key购买 nike

我正在尝试从文件中读取选择性信息。文件结构如下:

Component1:
Detail1
Detail2
Detail3

Component2:
Detail1
Detail2
Detail3

Component3:
Detail1
Detail2
Detail3

Component4:
Detail1
Detail2
Detail3

文件有限。行,我正在将该文件读入行列表。

with open('/tmp/filename.txt', 'r') as openf:
for line_no, line in enumerate(openf):
file_lines_list.append(line)

我想选择性的读取Component2的信息

所以我写了下面的代码。

with open('/tmp/filename.txt', 'r') as f:
for line_no, line in enumerate(f):
if "Component2" in line:
x = line_no
print(x)
for item in file_lines_list[x:]:
if item != "\n":
tmp_file.write(item)
else:
break

但是它打印行直到列表(文件行)的末尾。它不会在第一次出现换行符时中断,理想情况下应该是 Component3 之前的行。 (组件细节之间没有换行符)有人可以指出我在这里做错了什么吗?

最佳答案

使用 str.startswith()连同一个 bool 标志:

list.txt:

Component1:
C1_Detail1
C1_Detail2
C1_Detail3

Component2:
C2_Detail1
C2_Detail2
C2_Detail3

Component3:
C3_Detail1
C3_Detail2
C3_Detail3

Component4:
C4_Detail1
C4_Detail2
C4_Detail3

因此:

with open('list.txt', 'r') as f:
content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
bFlag = False
for line in content:
if line.startswith('Component2'):
bFlag = not bFlag
if bFlag:
if 'Component3' in line:
break
else:
print(line)

输出:

Component2:
C2_Detail1
C2_Detail2
C2_Detail3

关于python - 遍历字符串列表直到 string == newline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com