我有以下目录结构:
DICOMs:
Dir_1
/sub-dir 1
/sub-dir 2
/file1.dcm
Dir_2
/sub-dir 1
/sub-dir 2
/file1.dcm
我编写了以下代码来阅读每个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)
如果我在python控制台上运行它,它会给我
dirname = dir_1
dirnames=[subdir_1, subdir_2]
filenames = .DSstore
对于filenames数组中的此错误,我无法获取第一个文件的文件名。如果代码中有错误或语法错误,有人可以帮助我吗? 我在subdir_2和subdir_1下有file1.dcm。但仍显示的文件是.DS_Store。
我想要实现的是:
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
非常感谢!
答案 0 :(得分:2)
这可能更接近你的意图:
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
如果您只想对以.dcm
结尾的文件进行操作,那么这些内容可能会很好:
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
要专门解决您在问题中添加的新代码,我相信您会想要以下内容:
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