Reputation: 379
I have following directory structure:
DICOMs:
Dir_1
/sub-dir 1
/sub-dir 2
/file1.dcm
Dir_2
/sub-dir 1
/sub-dir 2
/file1.dcm
I have written following code to read first file of every sub_dir.
dire_str = '/DICOMs:/
for dirname,dirnames,filenames in os.walk(dire_str,topdown=True):
for subdirname in dirnames:
print(os.path.join(dirname,subdirname))
a = 1
for filename in filenames:
firstfilename = os.path.join(dirname, filename)
dcm_info = dicom.read_file(firstfilename, force=True)
If i run this on python console it gives me
dirname = dir_1
dirnames=[subdir_1, subdir_2]
filenames = .DSstore
FOr this error in filenames array i am not able to get filename of first file. Can some help me if there is error in code or if syntax is wrong ? I have file1.dcm under subdir_2 and subdir_1. But still file shown is .DS_Store.
What i am trying to implement is:
1) go into Dir(say dir_1)
go inside subdir_1
look for first .dcm file to read header tag
if tag is present in first file (yes) then call a function which will excute code on this subdir.(note i want to check just first file)
if not go out of this subdir
in this way check every subdir
once done with one dir
repeat these steps for dir2
Many thanks!
Upvotes: 1
Views: 432
Reputation: 787
This is probably closer to what you meant to do:
for dirpath, dirnames, filenames in os.walk(dire_str, topdown=True):
# Do some stuff that is per directory
for filename in filenames:
# Do some stuff that is per file
pass
And if you wish to only operate on files that end in .dcm
, something along these lines might be good:
for dirpath, dirnames, filenames in os.walk(dire_str, topdown=True):
# Do some stuff that is per directory
for filename in filenames:
if filename.endswith('.dcm')
# Do some stuff that is per file
pass
To specifically address the new bit of pseudo-code you added to the question, I believe you will want something like the following:
for dirpath, dirnames, filenames in os.walk(dire_str, topdown=True):
for filename in filenames:
if filename.endswith('.dcm') and tag_present_in_dcm(
os.path.join(dirpath, filename)
):
execute_code_on_subdir(dirpath)
break
Upvotes: 2