python – 由于不同的“循环样式”导致的不同行为

我有一个简单的问题.导航到罚款中的某一行,然后删除所有内容.我使用合适的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”语法…

最佳答案 从
Python documentation起,5.内置类型/ 5.9.文件对象:

In order to make a for loop the most
efficient way of looping over the
lines of a file (a very common
operation), the next() method uses a
hidden read-ahead buffer.

顺便说一句:通常不鼓励使用关键字(例如文件)作为变量名.

点赞