Skip to content

Commit 47f6b9f

Browse files
committed
FIX: TSV2JSON should convert empty TSV files to empty JSON files
1 parent e338802 commit 47f6b9f

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

niworkflows/interfaces/tests/test_utility.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""KeySelect tests."""
2+
from pathlib import Path
23
import pytest
34
from ..utility import KeySelect
5+
from ..utils import _tsv2json
46

57

68
def test_KeySelect():
@@ -10,3 +12,11 @@ def test_KeySelect():
1012

1113
with pytest.raises(ValueError):
1214
KeySelect(fields=[])
15+
16+
17+
def test_tsv2json(tmp_path):
18+
Path.write_bytes(tmp_path / 'empty.tsv', bytes())
19+
res = _tsv2json(tmp_path / 'empty.tsv', None, 'any_column')
20+
assert res == {}
21+
res = _tsv2json(tmp_path / 'empty.tsv', None, 'any_column', additional_metadata={'a': 'b'})
22+
assert res == {}

niworkflows/interfaces/utils.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -949,25 +949,31 @@ def camel(match):
949949

950950
# from fmriprep
951951
def less_breakable(a_string):
952-
""" hardens the string to different envs (i.e. case insensitive, no
953-
whitespace, '#' """
952+
"""hardens the string to different envs (i.e. case insensitive, no
953+
whitespace, '#'"""
954954
return "".join(a_string.split()).strip("#")
955955

956956
drop_columns = drop_columns or []
957957
additional_metadata = additional_metadata or {}
958-
tsv_data = pd.read_csv(in_tsv, sep="\t")
958+
try:
959+
tsv_data = pd.read_csv(in_tsv, "\t")
960+
except pd.errors.EmptyDataError:
961+
tsv_data = pd.DataFrame()
959962
for k, v in additional_metadata.items():
960963
tsv_data[k] = [v] * len(tsv_data.index)
961964
for col in drop_columns:
962965
tsv_data.drop(labels=col, axis="columns", inplace=True)
963-
tsv_data.set_index(index_column, drop=True, inplace=True)
966+
if index_column in tsv_data:
967+
tsv_data.set_index(index_column, drop=True, inplace=True)
964968
if enforce_case:
965969
tsv_data.index = [
966970
re.sub(re_to_snake, snake, less_breakable(i), 0).lower()
967971
for i in tsv_data.index
968972
]
969973
tsv_data.columns = [
970-
re.sub(re_to_camel, camel, less_breakable(i).title(), 0).replace("Csf", "CSF")
974+
re.sub(re_to_camel, camel, less_breakable(i).title(), 0).replace(
975+
"Csf", "CSF"
976+
)
971977
for i in tsv_data.columns
972978
]
973979
json_data = tsv_data.to_json(orient="index")

0 commit comments

Comments
 (0)