for 循环写入 (FURB122)
派生自 refurb 代码检查工具。
修复总是可用的。
作用
检查在 for 循环中使用 IOBase.write
的情况。
为什么这不好?
当写入一批元素时,更惯用的做法是使用单个方法调用 IOBase.writelines
,而不是逐个写入元素。
示例
from pathlib import Path
with Path("file").open("w") as f:
for line in lines:
f.write(line)
with Path("file").open("wb") as f_b:
for line_b in lines_b:
f_b.write(line_b.encode())
建议改为
from pathlib import Path
with Path("file").open("w") as f:
f.writelines(lines)
with Path("file").open("wb") as f_b:
f_b.writelines(line_b.encode() for line_b in lines_b)
修复安全性
如果此修复会导致注释被删除,则会被标记为不安全。