It's not clear to me what you want to do with each these multiple subfolders.
I hope this example will get you started.
I did my best to
- create an example directory tree
- iterate through it with
os.walk
- do something to a particular subfolder
I suggest learning about the Path
object from the pathlib
: https://docs.python.org/3/library/pathlib.html#basic-use
I wanted to copy the contents of a subdirectory so I imported shutil.
This is the sample tree I created:
folderC
├── patient001
│ └── subfolder 1
│ └── RTSTRUCT_085211_328790
│ └── RTSTRUCT
│ └── RTSTRUCT_085211_328790
│ └── RTSTRUCT_085211_328790.dcm
├── patient002
│ └── subfolder 2
│ └── RTSTRUCT_958381_489352
│ └── RTSTRUCT
│ └── RTSTRUCT_958381_489352
│ └── RTSTRUCT_958381_489352.dcm
└── patient003
└── subfolder 3
└── RTSTRUCT_731792_968907
└── RTSTRUCT
└── RTSTRUCT_731792_968907
└── RTSTRUCT_731792_968907.dcm
I then used the following code to to something to some particular subfolders:
?
import os
from pathlib import Path
import shutil
for root, dirnames, _ in os.walk("folderC"):
root_path = Path(root)
for dirname in dirnames:
dir_path = root_path / dirname
# Use conditionals at this point to select which directory you want to work with.
# For example.
# make a destination folder in all folders with "subfolder" in the name
if "subfolder" in dir_path.name:
destination = (dir_path / "10022" / "NIFTI")
destination.mkdir(exist_ok=True, parents=True)
# An example that copies the files from the deepest "RTSTRUCT_xxxx_xxxx" folder
# to the destination
if "RTSTRUCT_" in dir_path.name and dir_path.parent.name == "RTSTRUCT":
shutil.copytree(dir_path, destination, dirs_exist_ok=True)
This is the result. You can see the files from the "RSTRUCT_xxx_xxxx" directory is in the nearly created one inside of the "subfolder x" directory.
folderC
├── patient001
│ └── subfolder 1
│ ├── 10022
│ │ └── NIFTI
│ │ └── RTSTRUCT_085211_328790.dcm
│ └── RTSTRUCT_085211_328790
│ └── RTSTRUCT
│ └── RTSTRUCT_085211_328790
│ └── RTSTRUCT_085211_328790.dcm
├── patient002
│ └── subfolder 2
│ ├── 10022
│ │ └── NIFTI
│ │ └── RTSTRUCT_958381_489352.dcm
│ └── RTSTRUCT_958381_489352
│ └── RTSTRUCT
│ └── RTSTRUCT_958381_489352
│ └── RTSTRUCT_958381_489352.dcm
└── patient003
└── subfolder 3
├── 10022
│ └── NIFTI
│ └── RTSTRUCT_731792_968907.dcm
└── RTSTRUCT_731792_968907
└── RTSTRUCT
└── RTSTRUCT_731792_968907
└── RTSTRUCT_731792_968907.dcm
There are some simple examples in the Python documentation as well: https://docs.python.org/3/library/os.html#os.walk
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…