diff --git a/doc/whats_new.rst b/doc/whats_new.rst index f028de491..4d8030524 100644 --- a/doc/whats_new.rst +++ b/doc/whats_new.rst @@ -16,6 +16,9 @@ Changelog Bug ~~~ +- Allow regular strings as filenames in :meth:`~hnn_core.Cell_response.write` by + `Mainak Jas`_ in :gh:456. + API ~~~ diff --git a/hnn_core/cell_response.py b/hnn_core/cell_response.py index ee088c58c..f5e8f3912 100644 --- a/hnn_core/cell_response.py +++ b/hnn_core/cell_response.py @@ -376,8 +376,10 @@ def write(self, fname): Parameters ---------- fname : str - String format (e.g., '/spk_%d.txt') of the - path to the output spike file(s). + String format (e.g., 'spk_%d.txt' or 'spk_{0}.txt') of the + path to the output spike file(s). If no string format + is provided, the trial index will be automatically + appended to the file name. Outputs ------- @@ -387,9 +389,23 @@ def write(self, fname): 2) spike gid, and 3) gid type """ + fname = str(fname) + old_style = True + try: + fname % 0 + except TypeError: + fname.format(0) + old_style = False + except TypeError: + fname.replace('.txt', '_%d.txt') for trial_idx in range(len(self._spike_times)): - with open(str(fname) % (trial_idx,), 'w') as f: + if old_style: + this_fname = fname % (trial_idx,) + else: + this_fname = fname.format(trial_idx) + print(f'Writing file {this_fname}') + with open(this_fname, 'w') as f: for spike_idx in range(len(self._spike_times[trial_idx])): f.write('{:.3f}\t{}\t{}\n'.format( self._spike_times[trial_idx][spike_idx], diff --git a/hnn_core/tests/test_cell_response.py b/hnn_core/tests/test_cell_response.py index c49695b00..24d7c6db6 100644 --- a/hnn_core/tests/test_cell_response.py +++ b/hnn_core/tests/test_cell_response.py @@ -44,6 +44,8 @@ def test_cell_response(tmpdir): empty_spike = CellResponse(spike_times=[[], []], spike_gids=[[], []], spike_types=[[], []]) empty_spike.write(tmpdir.join('empty_spk_%d.txt')) + empty_spike.write(tmpdir.join('empty_spk.txt')) + empty_spike.write(tmpdir.join('empty_spk_{0}.txt')) assert empty_spike == read_spikes(tmpdir.join('empty_spk_*.txt')) assert ("CellResponse | 2 simulation trials" in repr(empty_spike))