[英]Read File From Directory with Multiple Files of the Same File Extension in Python
[英]read multiple files with same name but different extension Python
我試圖從具有相同名稱的文件夾中讀取和寫入文件,但具有不同的擴展名 => 從中提取數據 => 重寫。 這是我的代碼:
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)
我試圖做檢查:
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
但沒有成功文件的名稱是 sub01_T1w.json, sub01_T1w.nii.gz, sub01_T1w1.json, sub01_T1w1.nii.gz ...
我建議使用pathlib ,它是 python 標准庫的一個相對較新的部分,可以更輕松地處理路徑和文件。 使用它的解決方案可能如下所示:
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
如果你想給他們寫信,記得要帶重新打開目標open(json_path, 'w')
退出只讀后with
-塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.