52 lines
No EOL
2.5 KiB
Python
52 lines
No EOL
2.5 KiB
Python
import os
|
|
import shutil
|
|
|
|
def copy_last_file(source_base_dir, target_base_dir, modality):
|
|
# 確保目標目錄存在
|
|
os.makedirs(target_base_dir, exist_ok=True)
|
|
|
|
# 按照病患資料夾名稱進行排序
|
|
for patient_dir in sorted(os.listdir(source_base_dir)):
|
|
patient_path = os.path.join(source_base_dir, patient_dir)
|
|
if os.path.isdir(patient_path):
|
|
# 按照日期資料夾名稱進行排序
|
|
date_dirs = sorted(os.listdir(patient_path))
|
|
for date_dir in date_dirs:
|
|
date_path = os.path.join(patient_path, date_dir)
|
|
if os.path.isdir(date_path):
|
|
files = os.listdir(date_path)
|
|
|
|
# 篩選出 .nii.gz 和 .warp.nii.gz 檔案
|
|
nii_files = [f for f in files if f.endswith('.nii.gz')]
|
|
warp_files = [f for f in files if f.endswith('.warp.nii.gz')]
|
|
|
|
# 先選擇最後一個 .warp.nii.gz 檔案,如果沒有則選擇 .nii.gz 檔案
|
|
if warp_files:
|
|
warp_files.sort()
|
|
last_file = warp_files[-1] # 選擇最後一個 .warp.nii.gz 檔案
|
|
elif nii_files:
|
|
nii_files.sort()
|
|
last_file = nii_files[-1] # 選擇最後一個 .nii.gz 檔案
|
|
else:
|
|
print(f"No valid .nii.gz or .warp.nii.gz files found in {date_path}")
|
|
continue
|
|
|
|
last_file_path = os.path.join(date_path, last_file)
|
|
|
|
# 根據模態重新命名文件
|
|
new_file_name = f"{modality}_{patient_dir}.nii.gz"
|
|
target_file_path = os.path.join(target_base_dir, new_file_name)
|
|
|
|
# 複製文件到目標目錄
|
|
shutil.copy2(last_file_path, target_file_path)
|
|
print(f"Copied: {last_file_path} to {target_file_path}")
|
|
|
|
# T1C 模態的處理
|
|
source_base_dir_t1c = '/home/onlylian/sorted_modality_files/T1C'
|
|
target_base_dir_t1c = '/home/onlylian/T1C_image_folder'
|
|
copy_last_file(source_base_dir_t1c, target_base_dir_t1c, 'T1C')
|
|
|
|
# CT+CTC 模態的處理
|
|
source_base_dir_ctctc = '/home/onlylian/sorted_modality_files/CT+CTC'
|
|
target_base_dir_ctctc = '/home/onlylian/CT+CTC_image_folder'
|
|
copy_last_file(source_base_dir_ctctc, target_base_dir_ctctc, 'CT+CTC') |