From db08acf3e4e0f696a42164613b7342a1be0912f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jon=20Haitz=20Legarreta=20Gorro=C3=B1o?= Date: Sat, 5 Jul 2025 17:50:49 -0400 Subject: [PATCH] STYLE: Call `write` once instead of looping Call `write` once instead of looping by concatenating all strings that need to be written. Avoid using `writelines` as `ImageOpener` objects do not have that attribute. Fixes: ``` - for val in bvals: - fid.write(f'{val} ') + fid.writelines(f'{val} ' for val in bvals) ``` and other similar errors raised for example in: https://github.com/nipy/nibabel/actions/runs/16092302666/job/45410655457?pr=1422#step:7:23 Documentation: https://docs.astral.sh/ruff/rules/for-loop-writes/ --- nibabel/cmdline/parrec2nii.py | 9 +++------ nibabel/volumeutils.py | 3 +-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/nibabel/cmdline/parrec2nii.py b/nibabel/cmdline/parrec2nii.py index 0ae6b3fb4..aa8861042 100644 --- a/nibabel/cmdline/parrec2nii.py +++ b/nibabel/cmdline/parrec2nii.py @@ -358,8 +358,7 @@ def proc_file(infile, opts): ) with open(basefilename + '.bvals', 'w') as fid: # np.savetxt could do this, but it's just a loop anyway - for val in bvals: - fid.write(f'{val} ') + fid.write(' '.join(str(val) for val in bvals) + ' ') fid.write('\n') else: verbose('Writing .bvals and .bvecs files') @@ -369,13 +368,11 @@ def proc_file(infile, opts): bvecs = apply_affine(bv_reorient, bvecs) with open(basefilename + '.bvals', 'w') as fid: # np.savetxt could do this, but it's just a loop anyway - for val in bvals: - fid.write(f'{val} ') + fid.write(' '.join(str(val) for val in bvals) + ' ') fid.write('\n') with open(basefilename + '.bvecs', 'w') as fid: for row in bvecs.T: - for val in row: - fid.write(f'{val} ') + fid.write(' '.join(str(val) for val in row) + ' ') fid.write('\n') # export data labels varying along the 4th dimensions if requested diff --git a/nibabel/volumeutils.py b/nibabel/volumeutils.py index 41bff7275..c5ebbdd2c 100644 --- a/nibabel/volumeutils.py +++ b/nibabel/volumeutils.py @@ -830,8 +830,7 @@ def write_zeros(fileobj: io.IOBase, count: int, block_size: int = 8194) -> None: nblocks = int(count // block_size) rem = count % block_size blk = b'\x00' * block_size - for bno in range(nblocks): - fileobj.write(blk) + fileobj.write(blk * nblocks) fileobj.write(b'\x00' * rem)