i trying to read and write files from folder with same names, BUT different extensions => extract data from them => rewrite. Here is my code:
for header_name in glob.glob(os.path.join(folder_path, "*.json")):
for nii_name in glob.glob(os.path.join(folder_path, "*.nii")):
with open(header_name, "r") as f:
nii_meta = json.load(f)
add_stc = slicetime(header_name).tolist()
nii_meta["SliceTiming"] = add_stc
with open(header_name, 'w') as f:
json.dump(nii_meta, f, indent=2)
i tried to do check:
h_name = os.path.splitext(os.path.basename(header_name))[0]
n_name = os.path.splitext(os.path.basename(nii_name))[0]
if h_name == n_name:
do smth with data form files
but without succes Names of files are sub01_T1w.json, sub01_T1w.nii.gz, sub01_T1w1.json, sub01_T1w1.nii.gz ...
I'd suggest working with pathlib, it's a relatively new part of the python standard library that makes working with paths and files a bit easier. A solution using it could look like this:
from pathlib import Path
p = Path('parent/folder/of/my/files')
json_names = {f.stem for f in p.iterdir() if f.suffix == '.json'}
nii_names = {Path(f.stem).stem for f in p.iterdir() if f.suffixes == ['.nii', '.gz']}
for file_name in json_names & nii_names:
json_path = p / (file_name + '.json')
nii_path = p / (file_name + '.nii.gz')
with open(json_path) as json_file, open(nii_path) as nii_file:
... # do things with the files' contents
If you want to write to them, remember to re-open the target with open(json_path, 'w')
after exiting the read-only with
-block.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments