gpt4 book ai didi

python - 由于不同的 "looping styles"导致不同的行为

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:30 25 4
gpt4 key购买 nike

我有一个简单的问题。精细地导航到某一行,然后删除所有内容。我使用合适的 file.truncate() 调用。但是,下面两个代码片段的行为不同。

1)

with open(file, "a+b", 1) as f:
#Navigate to the MARKER
while True:
line = f.readline()
if MARKER in line:
f.truncate()
f.write(stuff)
break

2)

with open(file, "a+b", 1) as f:
#Navigate to the MARKER
for line in f:
if MARKER in line:
f.truncate()
f.write(stuff)
break

(1) 的行为符合预期。但是,在 (2) 的情况下,文件在找到 MARKER 后截断了几行。我推测正在进行一些缓冲,但如您所见,我明确地将缓冲行为定义为对 open() 调用的“行缓冲”。

有什么想法吗?我想使用更直观的“for line in file”语法...

最佳答案

线索好像在this bit of Python's C source -- Python 2.7 似乎为 for line in file: 使用 8 KB 预读缓冲区。

关于python - 由于不同的 "looping styles"导致不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5631463/

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