gpt4 book ai didi

python - 循环遍历文件并同时使用 `file.readline()` 是 "ok"的做法吗?

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

我编写了一段代码,其中在遍历文件中的行的 for 循环中,我有一些 file.readline() 语句。尽管脚本似乎运行良好,但这对我来说似乎很有问题。为了演示,假设您的文件中有以下内容:

...bla bla

Header signifying important stuff are coming

important stuff line 1

important stuff line 2

important stuff line 3

...bla bla

标题和重要内容行 block 出现多次,因此我的脚本看起来大致如下:

with open(file, 'r') as fi:
for line in fi:
if header in line:
a = fi.readline()
b = fi.readline()
c = fi.readline()
continue

for line in fifi.readline() 都消耗相同的对象(文件),因此在 continue 之后, line 的下一个值将是向下 4 行,因为 readline() 调用消耗了 3 行。

正如我所说,上述方法有效,但我并不是“如果有效,就不愚蠢”运动的大力支持者。

另一方面,另一种方法是:

found_header = True
with open(file, 'r') as fi:
for line in fi:
if header in line:
new_stuff_inc = []
found_header = True
elif found_header:
new_stuff_inc.append(line)
if len(new_stuff_inc) == 3:
found_header = False

这似乎更安全,因为文件一次喂一张嘴(只有for line..消耗它),但它看起来不必要地复杂..

那么,应该如何去做这样的事情呢?

最佳答案

混合 forreadline() 不是很令人满意,你是对的,顺便说一句,它不起作用,所以第一个片段的问题解决了:) (使用 Python 2.7 进行测试)

Traceback (most recent call last):
File "<module1>", line 3, in <module>
ValueError: Mixing iteration and read methods would lose data

Python 只是不会接受逐行迭代文件和 readline(有点像迭代列表并从中删除元素,只不过这里它是 protected ) )

创建一个能够单独使用 for 的状态机既麻烦又容易出错。

你可以尝试另一种方法:

with open(file, 'r') as fi:
while True:
line = fi.readline()
if not line: # end of file
break
if header in line:
a = fi.readline()
b = fi.readline()
c = fi.readline()
continue

关于python - 循环遍历文件并同时使用 `file.readline()` 是 "ok"的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40915421/

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