gpt4 book ai didi

python - 如何在 python 中开始和结束读取特定字符串的文件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:10 24 4
gpt4 key购买 nike

如何开始和结束读取特定字符串的文件?

例如:

start file
some data
start point
some data
end point
some data
end file

到目前为止我的情况是:

filename = 'name of file'
with open(filename) as f:
for line in iter(lambda: f.readline().rstrip(), 'end point'):
print(line)

最佳答案

这实际上取决于您是否正在读取 n 行,或者读取所有行直到遇到包含子字符串的特定行。

三个例子:

# Ready file until 'end point' is encountered in a line
with open('sample.txt') as f:
for line in f:
# ... do things with the line
print(line)
if 'end point' in line:
print('---')
break

# Read the first 5 lines
with open('sample.txt') as f:
lines = [next(f) for x in range(5)]
print(lines)

# Less performant, read all lines and then slice
with open('sample.txt') as f:
all_lines = f.readlines()
print(lines[:5])

关于python - 如何在 python 中开始和结束读取特定字符串的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113695/

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