我有以下目录结构:
DICOMs:
Dir_1
/sub-dir 1
/sub-dir 2
/file1.dcm
Dir_2
/sub-dir 1
/sub-dir 2
/file1.dcm
我编写了以下代码来读取每个子目录的第一个文件。
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
对于文件名数组中的此错误,我无法获取第一个文件的文件名。如果代码有错误或语法错误,有人可以帮助我吗? 我在 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
非常感谢!
最佳答案
这可能更接近您的意图:
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
关于Python:无法在我的代码中找到错误。 os.walk() 返回的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28589591/