Python,循环打开文件 (dicom)

Python, Opening files in loop (dicom)

我目前正在使用代码手动读取 200 张 dicom 图像:

ds1 = dicom.read_file('1.dcm')

到目前为止,这已经奏效了,但我试图通过创建一个循环来使用以下代码读取文件,从而使我的代码更短且更易于使用:

for filename in os.listdir(dirName):
    dicom_file = os.path.join("/",dirName,filename)   
    exists = os.path.isfile(dicom_file) 
    print filename
    ds = dicom.read_file(dicom_file)

此代码当前无效,我收到错误消息:

"raise InvalidDicomError("File is missing 'DICM' marker. "
dicom.errors.InvalidDicomError: File is missing 'DICM' marker. Use         
force=True to force reading

谁能告诉我哪里出错了?

尝试添加:

dicom_file = os.path.join("/",dirName,filename) 
if not dicom_file.endswith('.dcm'):
    continue 

我认为行:

dicom_file = os.path.join("/",dirName,filename) 

可能是个问题?它将连接所有三个以形成以“/”为根的路径。例如:

os.path.join("/","directory","file")

会给你“/directory/file”(绝对路径),而:

os.path.join("directory","file")

会给你"directory/file"(相对路径)

如果你知道你要的文件都是“*.dcm” 你可以尝试 glob 模块:

import glob

files_with_dcm = glob.glob("*.dcm")

这也适用于完整路径:

import glob

files_with_dcm = glob.glob("/full/path/to/files/*.dcm")

而且,os.listdir(dirName) 将包括目录中的所有内容,包括其他目录、点文件和诸如此类的东西

如果您在阅读前使用 "if exists:",您的 exists = os.path.isfile(dicom_file) 行将过滤掉所有非文件。

如果你知道模式,我会推荐 glob 方法,否则:

if exists:
   try:
      ds = dicom.read_file(dicom_file)
   except InvalidDicomError as exc:
      print "something wrong with", dicom_file

如果您执行 try/except,if exists: 有点多余,但不会造成伤害...