1

I have 20,000 PosixPath, each one pointing at a different .dcm object. I need to read .dcm objects one by one. Here is my code so far:

from pathlib import Path
import glob
import dicom
data = Path('/data')
path_to_dcm_objects = list(data.glob('**/*.dcm'))
for i in len(path_to_dcm_objects):
    record = dicom.read_file(path_to_dcm_objects[i])

I get an error when I want to read a .dcm file using its PosixPath:

AttributeError: 'PosixPath' object has no attribute 'read'

Any help would be appreciated.

4

1 回答 1

2

dicom.read_file()需要一个打开的文件对象或路径而不是Path实例的字符串。如果它不是字符串,它认为它是一个打开的文件并尝试从中读取。

Path实例转换为字符串str(path_object)

for i in len(path_to_dcm_objects):
    record = dicom.read_file(str(path_to_dcm_objects[i]))

Path对象转换为字符串的帮助:

返回路径的字符串表示,适合传递给系统调用。

您还可以使用:

 path_object.as_posix()

这为您提供了一个 Posix 路径:

返回带有正斜杠 (/) 的路径的字符串表示形式。

顺便说一句,遍历所有路径的 Pythonic 方式看起来更像这样:

for path_obj in data.glob('**/*.dcm'):
    record = dicom.read_file(str(path_obj))
于 2018-03-04T16:00:46.093 回答