python - Different behavior due to different "looping styles" -
i have simple problem. navigate line in fine, , delete after that. use suitable file.truncate() call. however, 2 snippets of code below behave differently.
1)
with open(file, "a+b", 1) f: #navigate marker while true: line = f.readline() if marker in line: f.truncate() f.write(stuff) break 2)
with open(file, "a+b", 1) f: #navigate marker line in f: if marker in line: f.truncate() f.write(stuff) break (1) behaves expected. in case of (2), file in truncated several lines after marker found. speculate there buffering going on, can see, explicitly define buffering behavior "line buffered" open() call.
any thoughts? use more intuitive "for line in file" syntax...
from python documentation, 5. built-in types / 5.9. file objects:
in order make loop efficient way of looping on lines of file (a common operation), next() method uses hidden read-ahead buffer.
btw: discouraged use keywords (e.g. file) variable names.
Comments
Post a Comment