2

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.

user9439906
  • 433
  • 2
  • 7
  • 17
  • Are you sure that didn't mean `import pydicom`? – Mike Müller Mar 04 '18 at 15:55
  • @MikeMüller I used `pip install pydicom` to install. Then I used `import dicom` to use the module. The system does not recognize `import pydicom` – user9439906 Mar 04 '18 at 16:01
  • I get *This code is using an older version of pydicom, which is no longer maintained as of Jan 2017. You can access the new pydicom features and API by installing `pydicom` from PyPI. See 'Transitioning to pydicom 1.x' section at pydicom.readthedocs.org for more information.* – Mike Müller Mar 04 '18 at 16:03
  • @MikeMüller I will check that out. Many thanks! – user9439906 Mar 04 '18 at 16:07

1 Answers1

3

dicom.read_file() needs an open file object or a string for the path not a Path instance. If it is not a strings it considers it an open file and tries to read from it.

Convert the Path instance to a string with str(path_object):

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

The help for converting a Path object into a string:

Return the string representation of the path, suitable for passing to system calls.

You can also use:

 path_object.as_posix()

This gives you a Posix path:

Return the string representation of the path with forward (/) slashes.

BTW, the pythonic way to iterate over all paths would look more like this:

for path_obj in data.glob('**/*.dcm'):
    record = dicom.read_file(str(path_obj))
Mike Müller
  • 82,630
  • 20
  • 166
  • 161