8000 STY: Apply ruff/flake8-simplify rules (SIM) by DimitriPapadopoulos · Pull Request #3676 · nipy/nipype · GitHub
[go: up one dir, main page]

Skip to content

STY: Apply ruff/flake8-simplify rules (SIM) #3676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 6, 2024
Merged
Prev Previous commit
Next Next commit
STY: Apply ruff/flake8-simplify rule SIM115
SIM115 Use a context manager for opening files
  • Loading branch information
DimitriPapadopoulos committed Oct 6, 2024
commit d294476c7b43deed1dbf0cdd089eb89d54283117
33 changes: 14 additions & 19 deletions nipype/interfaces/fsl/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,12 @@ class Level1Design(BaseInterface):
output_spec = Level1DesignOutputSpec

def _create_ev_file(self, evfname, evinfo):
f = open(evfname, "w")
for i in evinfo:
if len(i) == 3:
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
else:
f.write("%f\n" % i[0])
f.close()
with open(evfname, "w") as f:
for i in evinfo:
if len(i) == 3:
f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n")
else:
f.write("%f\n" % i[0])

def _create_ev_files(
self,
Expand Down Expand Up @@ -403,9 +402,8 @@ def _run_interface(self, runtime):
fsf_txt += cond_txt
fsf_txt += fsf_postscript.substitute(overwrite=1)

f = open(os.path.join(cwd, "run%d.fsf" % i), "w")
f.write(fsf_txt)
f.close()
with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f:
f.write(fsf_txt)

return runtime

Expand Down Expand Up @@ -946,9 +944,8 @@ def _run_interface(self, runtime):
for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)):
fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir))
fsf_txt += fsf_footer.substitute()
f = open(os.path.join(os.getcwd(), "register.fsf"), "w")
f.write(fsf_txt)
f.close()
with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f:
f.write(fsf_txt)

return runtime

Expand Down Expand Up @@ -1414,9 +1411,8 @@ def _run_interface(self, runtime):

# write design files
for i, name in enumerate(["design.mat", "design.con", "design.grp"]):
f = open(os.path.join(cwd, name), "w")
f.write(txt[name])
f.close()
with open(os.path.join(cwd, name), "w") as f:
f.write(txt[name])

return runtime

Expand Down Expand Up @@ -1583,9 +1579,8 @@ def _run_interface(self, runtime):
if ("fts" in key) and (nfcons == 0):
continue
filename = key.replace("_", ".")
f = open(os.path.join(cwd, filename), "w")
f.write(val)
f.close()
with open(os.path.join(cwd, filename), "w") as f:
f.write(val)

return runtime

Expand Down
23 changes: 10 additions & 13 deletions nipype/interfaces/nitime/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,13 @@ def _read_csv(self):

"""
# Check that input conforms to expectations:
first_row = open(self.inputs.in_file).readline()
with open(self.inputs.in_file) as f:
first_row = f.readline()
if not first_row[1].isalpha():
raise ValueError(
"First row of in_file should contain ROI names as strings of characters"
)

roi_names = (
open(self.inputs.in_file).readline().replace('"', "").strip("\n").split(",")
)
roi_names = first_row.replace('"', "").strip("\n").split(",")
# Transpose, so that the time is the last dimension:
data = np.loadtxt(self.inputs.in_file, skiprows=1, delimiter=",").T

Expand Down Expand Up @@ -255,16 +253,15 @@ def _make_output_files(self):
tmp_f = tempfile.mkstemp()[1]
np.savetxt(tmp_f, this[0], delimiter=",")

fid = open(
with open(
fname_presuffix(self.inputs.output_csv_file, suffix="_%s" % this[1]),
"w+",
)
# this writes ROIs as header line
fid.write("," + ",".join(self.ROIs) + "\n")
# this writes ROI and data to a line
for r, line in zip(self.ROIs, open(tmp_f)):
fid.write(f"{r},{line}")
fid.close()
) as fid:
# this writes ROIs as header line
fid.write("," + ",".join(self.ROIs) + "\n")
# this writes ROI and data to a line
for r, line in zip(self.ROIs, open(tmp_f)):
fid.write(f"{r},{line}")

def _make_output_figures(self):
"""
Expand Down
50 changes: 24 additions & 26 deletions nipype/interfaces/slicer/generate_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,22 @@ def force_to_valid_python_variable_name(old_name):

def add_class_to_package(class_codes, class_names, module_name, package_dir):
module_python_filename = os.path.join(package_dir, "%s.py" % module_name)
f_m = open(module_python_filename, "w")
f_i = open(os.path.join(package_dir, "__init__.py"), "a+")
f_m.write(
"""# -*- coding: utf-8 -*-
with (
open(module_python_filename, "w") as f_m,
open(os.path.join(package_dir, "__init__.py"), "a+") as f_i,
):
f_m.write(
"""# -*- coding: utf-8 -*-
\"\"\"Autogenerated file - DO NOT EDIT
If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n"""
)
imports = """\
)
imports = """\
from ..base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec,
File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath)
import os\n\n\n"""
f_m.write(imports)
f_m.write("\n\n".join(class_codes))
f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names)))
f_m.close()
f_i.close()
f_m.write(imports)
f_m.write("\n\n".join(class_codes))
f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names)))


def crawl_code_struct(code_struct, package_dir):
Expand All @@ -70,9 +70,8 @@ def crawl_code_struct(code_struct, package_dir):
if l2:
v = l2
subpackages.append(k.lower())
f_i = open(os.path.join(package_dir, "__init__.py"), "a+")
f_i.write("from %s import *\n" % k.lower())
f_i.close()
with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i:
f_i.write("from %s import *\n" % k.lower())
new_pkg_dir = os.path.join(package_dir, k.lower())
if os.path.exists(new_pkg_dir):
rmtree(new_pkg_dir)
Expand All @@ -88,9 +87,9 @@ def crawl_code_struct(code_struct, package_dir):
list(v.values()), list(v.keys()), module_name, package_dir
)
if subpackages:
f = open(os.path.join(package_dir, "setup.py"), "w")
f.write(
"""# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
with open(os.path.join(package_dir, "setup.py"), "w") as f:
f.write(
8000 """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
Expand All @@ -105,16 +104,15 @@ def configuration(parent_package='',top_path=None):
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
""".format(
pkg_name=package_dir.split("/")[-1],
sub_pks="\n ".join(
[
"config.add_data_dir('%s')" % sub_pkg
for sub_pkg in subpackages
]
),
pkg_name=package_dir.split("/")[-1],
sub_pks="\n ".join(
[
"config.add_data_dir('%s')" % sub_pkg
for sub_pkg in subpackages
]
),
)
)
)
f.close()


def generate_all_classes(
Expand Down
6 changes: 2 additions & 4 deletions tools/checkspecs.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,8 @@ def _parse_module(self, uri):
if filename is None:
# nothing that we could handle here.
return ([], [])
f = open(filename)
functions, classes = self._parse_lines(f, uri)
f.close()
return functions, classes
with open(filename) as f:
return self._parse_lines(f, uri)

def _parse_lines(self, linesource, module):
"""Parse lines of text for functions and classes"""
Expand Down
0