Skip to content

win_access

win_access Documentation

A module to access Mobile Devices from Windows via USB connection. Implements access to basic functions of the Windows WPD API

Author: Heribert Füchtenhans

Version: 2025.6.26

For examples please look into the examples directory.

All functions through IOError when a communication fails.

Requirements
  • OS
    • Windows 10
    • Windows 11
  • Python modules
    • comtypes

The module contains the following functions:

  • 'get_portable_devices' Get a list (instances of PortableDevice) of all connected portable devices.
  • 'get_content_from_device_path' - Get the content (files, dirs) of a path as instances of PortableDeviceContent
  • 'walk' - Iterates ower all files in a tree.
  • 'makedirs' - Creates the directories on the MTP device if they don't exist.

The module contains the following classes:

  • 'PortableDevice' - Class for one portable device found connected
  • 'PortableDeviceContent' - Class for one file, directory or storage

Information to the filenames used in MTP: - The filename consists of the following part: devicename/storagename/foldername/.... - The devicename can be found in PortableDevice.devicename - The storagename is in content returned by PortableDevice.get_content It's the the name attribute - Every PortableDeviceContent has an attribute 'full_filename' that contains the whole path of that content

Examples:

>>> import mtp.win_access
>>> devs = mtp.win_access.get_portable_devices()
>>> len(devs) >= 1
True
>>> str(devs[0])[:33]
'PortableDevice: PLEGAR1791402808 '
>>> devs[0].close()

PortableDevice

Class with the infos for a connected portable device. This instances of this class are created intern, please only use the methods and attributes

Methods:

Name Description
close

Must be called when the device is no more needed. This frees the resources

get_content

Get the content (Storages) of the device

Attributes:

Name Type Description
name

Name of the MTP device

description

Description for the device

serialnumber

Serialnumber of the device

devicename

The full name of the device. Use it when building pathes

Raises:

Type Description
IOError

If something went wrong

Source code in mtp/win_access.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
class PortableDevice:
    """Class with the infos for a connected portable device.
    This instances of this class are created intern, please only use the methods and attributes

    Methods:
        close: Must be called when the device is no more needed. This frees the resources
        get_content: Get the content (Storages) of the device

    Attributes:
        name: Name of the MTP device
        description: Description for the device
        serialnumber: Serialnumber of the device
        devicename: The full name of the device. Use it when building pathes

    Exceptions:
        IOError: If something went wrong
    """

    # Class variable
    _properties_to_read: types.PortableDeviceKeyCollection | None = None

    def __init__(self, p_id: str) -> None:
        """Init the class.

        Parameters:
            p_id: ID of the found device
        """
        self._p_id = p_id
        self._set_device()
        self.name, self.description = self._get_description()
        # Get the serialnumber
        self._pdc = PortableDeviceContent(ctypes.c_wchar_p("DEVICE"), self._device.Content(), self, None)
        self.serialnumber = self._pdc._serialnumber
        self.devicename = f"{self.name}_{self.description}_{self.serialnumber}"
        # Correct filename because during the initialisation it's only filled
        # with the name, not name and serialnumber
        self._pdc.full_filename = self.devicename

    def close(self) -> None:
        """Close the connection to the device. This must be called when the device is no more needed."""
        comtypes.CoUninitialize()

    def _get_description(self) -> tuple[str, str]:
        """Get the name and the description of the device. If no description is available
        name and description will be identical.

        Returns:
            A tuple with of name, description

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> dev[0]._get_description()
            ('Nokia 6', 'Nokia 6')
        """
        if DEVICE_MANAGER is None:
            return "", ""
        name_len = ctypes.pointer(ctypes.c_ulong(0))
        DEVICE_MANAGER.GetDeviceDescription(self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len)
        name = ctypes.create_unicode_buffer(name_len.contents.value)
        DEVICE_MANAGER.GetDeviceDescription(
            self._p_id,
            ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
            name_len,
        )
        self._desc = name.value
        try:
            DEVICE_MANAGER.GetDeviceFriendlyName(self._p_id, ctypes.POINTER(ctypes.c_ushort)(), name_len)
            name = ctypes.create_unicode_buffer(name_len.contents.value)
            DEVICE_MANAGER.GetDeviceFriendlyName(
                self._p_id,
                ctypes.cast(name, ctypes.POINTER(ctypes.c_ushort)),
                name_len,
            )
            self._name = name.value
        except comtypes.COMError:  # pyright: ignore[reportAttributeAccessIssue]
            self._name = self._desc
        return self._name, self._desc

    def _set_device(self):
        """Open a device and sets self._device"""
        client_information = comtypes.client.CreateObject(
            types.PortableDeviceValues,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceValues
        )
        self._device = comtypes.client.CreateObject(
            port.PortableDevice,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDevice
        )
        if self._device is not None:
            self._device.Open(self._p_id, client_information)

    def get_content(self) -> list[PortableDeviceContent]:
        """Get the content of a device, the storages

        Returns:
            A list of instances of PortableDeviceContent, one for each storage

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()
            >>> len(stor)
            2
            >>> str(stor[0])
            'PortableDeviceContent Interner gemeinsamer Speicher (0)'
            >>> dev[0].close()
        """
        return list(self._pdc.get_children())

    def __repr__(self) -> str:
        return f"PortableDevice: {self.serialnumber} ({self.name})"

__init__(p_id)

Init the class.

Parameters:

Name Type Description Default
p_id str

ID of the found device

required
Source code in mtp/win_access.py
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def __init__(self, p_id: str) -> None:
    """Init the class.

    Parameters:
        p_id: ID of the found device
    """
    self._p_id = p_id
    self._set_device()
    self.name, self.description = self._get_description()
    # Get the serialnumber
    self._pdc = PortableDeviceContent(ctypes.c_wchar_p("DEVICE"), self._device.Content(), self, None)
    self.serialnumber = self._pdc._serialnumber
    self.devicename = f"{self.name}_{self.description}_{self.serialnumber}"
    # Correct filename because during the initialisation it's only filled
    # with the name, not name and serialnumber
    self._pdc.full_filename = self.devicename

close()

Close the connection to the device. This must be called when the device is no more needed.

Source code in mtp/win_access.py
667
668
669
def close(self) -> None:
    """Close the connection to the device. This must be called when the device is no more needed."""
    comtypes.CoUninitialize()

get_content()

Get the content of a device, the storages

Returns:

Type Description
list[PortableDeviceContent]

A list of instances of PortableDeviceContent, one for each storage

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()
>>> len(stor)
2
>>> str(stor[0])
'PortableDeviceContent Interner gemeinsamer Speicher (0)'
>>> dev[0].close()
Source code in mtp/win_access.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def get_content(self) -> list[PortableDeviceContent]:
    """Get the content of a device, the storages

    Returns:
        A list of instances of PortableDeviceContent, one for each storage

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()
        >>> len(stor)
        2
        >>> str(stor[0])
        'PortableDeviceContent Interner gemeinsamer Speicher (0)'
        >>> dev[0].close()
    """
    return list(self._pdc.get_children())

PortableDeviceContent

Class for one file, directory or storage with it's properties. This instances of this class are created intern, please only use the methods and attributes

Methods:

Name Description
get_children

Get the children of this content (files and directories)

get_child

Returns a PortableDeviceContent for one child whos name is known.

get_path

Returns a PortableDeviceContent for a child who's path in the tree is known.

create_content

Creates an empty directory content in this content.

upload_file

Upload of a file to MTP device.

download_file

Download a file from MTP device.

remove

Deletes the current directory or file.

Attributes:

Name Type Description
name str

Directory-/Filename of this content

fullname str

The full path name

date_modified datetime

The file modification date

size int

The size of the file in bytes

content_type int

Type of the entry. One of the WPD_CONTENT_TYPE_ constants:

  • WPD_CONTENT_TYPE_UNDEFINED = -1
  • WPD_CONTENT_TYPE_STORAGE = 0
  • WPD_CONTENT_TYPE_DIRECTORY = 1
  • WPD_CONTENT_TYPE_FILE = 2
  • WPD_CONTENT_TYPE_DEVICE = 3

Raises:

Type Description
IOError

If something went wrong

Source code in mtp/win_access.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
class PortableDeviceContent:
    """Class for one file, directory or storage with it's properties.
    This instances of this class are created intern, please only use the methods and attributes

    Methods:
        get_children: Get the children of this content (files and directories)
        get_child: Returns a PortableDeviceContent for one child whos name is known.
        get_path: Returns a PortableDeviceContent for a child who's path in the tree is known.
        create_content: Creates an empty directory content in this content.
        upload_file: Upload of a file to MTP device.
        download_file: Download a file from MTP device.
        remove: Deletes the current directory or file.

    Attributes:
        name: Directory-/Filename of this content
        fullname: The full path name
        date_modified: The file modification date
        size: The size of the file in bytes
        content_type: Type of the entry. One of the WPD_CONTENT_TYPE_ constants:

            - WPD_CONTENT_TYPE_UNDEFINED = -1
            - WPD_CONTENT_TYPE_STORAGE = 0
            - WPD_CONTENT_TYPE_DIRECTORY = 1
            - WPD_CONTENT_TYPE_FILE = 2
            - WPD_CONTENT_TYPE_DEVICE = 3

    Exceptions:
        IOError: If something went wrong
    """

    # class variable
    _properties_to_read: types.PortableDeviceKeyCollection | None = None

    _CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree
    _CoTaskMemFree.restype = None
    _CoTaskMemFree.argtypes = [ctypes.c_void_p]

    def __init__(
        self,
        object_id: Any,
        content: "PortableDeviceContent",
        device: "PortableDevice",
        properties: Any | None = None,
        parent_path: str = "",
    ) -> None:
        """Instance constructor"""

        self._object_id = object_id
        self._content: "PortableDeviceContent" = content
        self._parent_path = parent_path
        self.name: str = ""
        self._plain_name: str = ""
        self.content_type: int = WPD_CONTENT_TYPE_UNDEFINED
        self.full_filename: str = ""
        self.size: int = -1
        self.date_modified: datetime.datetime = datetime.datetime.now()
        self._serialnumber: str = ""
        self._port_device = device
        self._properties = properties or content.properties()  # pyright: ignore[reportAttributeAccessIssue]
        if PortableDeviceContent._properties_to_read is None:
            # We haven't set the properties wie will read, so do it now
            PortableDeviceContent._properties_to_read = comtypes.client.CreateObject(
                types.PortableDeviceKeyCollection,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDeviceKeyCollection
            )
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_NAME)  # pyright: ignore[reportOptionalMemberAccess]
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_ORIGINAL_FILE_NAME)  # pyright: ignore[reportOptionalMemberAccess]
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_CONTENT_TYPE)  # pyright: ignore[reportOptionalMemberAccess]
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_SIZE)  # pyright: ignore[reportOptionalMemberAccess]
            PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_MODIFIED)  # pyright: ignore[reportOptionalMemberAccess]
            PortableDeviceContent._properties_to_read.Add(WPD_DEVICE_SERIAL_NUMBER)  # pyright: ignore[reportOptionalMemberAccess]
        self._get_properties()

    def _get_properties(
        self,
    ) -> None:
        """Sets the properties of this content."""
        propvalues = self._properties.GetValues(
            self._object_id, PortableDeviceContent._properties_to_read
        )
        self.content_type = WPD_CONTENT_TYPE_UNDEFINED
        try:
            self._plain_name = str(propvalues.GetStringValue(WPD_OBJECT_NAME))
        except comtypes.COMError:  # pyright: ignore[reportAttributeAccessIssue]
            self.content_type = WPD_CONTENT_TYPE_DIRECTORY
            self.name = self._plain_name = ""
        try:
            self.name = self._plain_name = str(propvalues.GetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME))
        except comtypes.COMError:  # pyright: ignore[reportAttributeAccessIssue]
            self.name = self._plain_name
        content_id = str(propvalues.GetGuidValue(WPD_OBJECT_CONTENT_TYPE))
        if content_id in {
            "{23F05BBC-15DE-4C2A-A55B-A9AF5CE412EF}",
            "{99ED0160-17FF-4C44-9D98-1D7A6F941921}",
        }:
            # It's a storage
            with contextlib.suppress(comtypes.COMError):  # pyright: ignore[reportAttributeAccessIssue]
                self._serialnumber = str(propvalues.GetStringValue(WPD_DEVICE_SERIAL_NUMBER))
            self.content_type = WPD_CONTENT_TYPE_STORAGE
        else:
            if content_id == "{27E2E392-A111-48E0-AB0C-E17705A05F85}":
                self.content_type = WPD_CONTENT_TYPE_DIRECTORY
            else:
                self.content_type = WPD_CONTENT_TYPE_FILE
            self.size = int(propvalues.GetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE))
            x = propvalues.GetValue(WPD_OBJECT_DATE_MODIFIED)
            filetime = float(getattr(propvalues.GetValue(WPD_OBJECT_DATE_MODIFIED), "__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001").date)
            # filetime = float(propvalues.GetFloatValue(WPD_OBJECT_DATE_MODIFIED).__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001.date)
            filedate = abs(int(filetime))
            days_since_1970 = filedate - (datetime.datetime(1970, 1, 1) - datetime.datetime(1899, 12, 30)).days
            hours = (filetime - int(filetime)) * 24
            minutes = (hours - int(hours)) * 60
            seconds = (minutes - int(minutes)) * 60
            milliseconds = round((seconds - int(seconds)) * 1000)
            self.date_modified = datetime.datetime(1970, 1, 1) + datetime.timedelta(
                days=days_since_1970,
                hours=int(hours),
                minutes=int(minutes),
                seconds=int(seconds),
                milliseconds=milliseconds,
            )
        propvalues.Clear()
        self.full_filename = os.path.join(self._parent_path, self._plain_name)

    def get_children(self) -> collections.abc.Generator["PortableDeviceContent", None, None]:
        """Get the child items (dirs and files) of a folder.

        Returns:
            A Generator of PortableDeviceContent instances each representing a child entry.

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> str(list(stor.get_children())[0])
            'PortableDeviceContent Pictures (1)'
            >>> dev[0].close()
        """
        try:
            enumobject_ids = self._content.EnumObjects(  # pyright: ignore[reportAttributeAccessIssue]
                ctypes.c_ulong(0),
                self._object_id,
                ctypes.POINTER(port.IPortableDeviceValues)(),
            )
            while True:
                num_fetched = ctypes.pointer(ctypes.c_ulong(0))
                # Always load only one entry
                object_id_array = enumobject_ids.Next(
                    1,
                    num_fetched,
                )
                if num_fetched.contents.value == 0:
                    break
                curobject_id = str(object_id_array[0])
                value = PortableDeviceContent(curobject_id, self._content, self._port_device, self._properties, self.full_filename)
                yield value
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error getting child item from '{self.full_filename}': {err.args[1]}")

    def get_child(self, name: str) -> "PortableDeviceContent | None":
        """Returns a PortableDeviceContent for one child whos name is known.
        The search is case sensitive.

        Parameters:
            name: The name of the file or directory to search

        Returns:
            The PortableDeviceContent instance of the child or None if the child could not be found.

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> str(list(stor.get_children())[0])
            'PortableDeviceContent Pictures (1)'
            >>> dev[0].close()
        """
        matches = [c for c in self.get_children() if c.name == name]
        return matches[0] if matches else None

    def get_path(self, path: str) -> "PortableDeviceContent | None":
        """Returns a PortableDeviceContent for a child who's path in the tree is known.
        The path can be fully qualified or starting from the current content.

        Parameters:
            path: The pathname to the child.

        Returns:
            The PortableDeviceContent instance of the child or None if the child could not be found.

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> str(stor.get_path(f"{stor.full_filename}/DCIM"))
            'PortableDeviceContent DCIM (1)'
            >>> str(stor.get_path(f"DCIM"))
            'PortableDeviceContent DCIM (1)'
            >>> dev[0].close()
        """
        name = path.replace("/", os.path.sep)
        start = name.split(os.sep, 1)[0]
        if start == self._port_device.devicename:
            return get_content_from_device_path(self._port_device, name)
        if start == self.name:
            name = name.split(os.sep, 1)[1]
        cur: "PortableDeviceContent | None" = self
        for part in name.split(os.path.sep):
            if not cur:
                return None
            cur = cur.get_child(part)
        return cur

    def __repr__(self) -> str:
        """String representation"""
        return f"PortableDeviceContent {self.name} ({self.content_type})"

    def create_content(self, dirname: str) -> "PortableDeviceContent":
        """Creates an empty directory content in this content.

        Parameters:
            dirname: Name of the directory that shall be created

        Returns:
            PortableDeviceContent for the new directory

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> mycont = stor.get_path(f"{stor.full_filename}/MyMusic")
            >>> if mycont: _ = mycont.remove()
            >>> cont = stor.create_content("MyMusic")
            >>> cont.full_filename
            'Nokia 6_Nokia 6_PLEGAR1791402808\\\\Interner gemeinsamer Speicher\\\\MyMusic'
            >>> dev[0].close()
        """
        pdc = None
        try:
            object_properties = comtypes.client.CreateObject(
                types.PortableDeviceValues,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDeviceValues,
            )
            object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)
            object_properties.SetStringValue(WPD_OBJECT_NAME, dirname)
            object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, dirname)
            object_properties.SetGuidValue(WPD_OBJECT_CONTENT_TYPE, WPD_CONTENT_TYPE_FOLDER_GUID)
            self._content.CreateObjectWithPropertiesOnly(  # pyright: ignore[reportAttributeAccessIssue]
                object_properties, ctypes.POINTER(ctypes.c_wchar_p)()
            )
            pdc = self.get_child(dirname)
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error creating directory '{dirname}': {err.args[1]}")
        finally:
            object_properties = None
        if pdc is None:
            raise IOError(f"Error creating directory '{dirname}': Could not get conent of new directory")
        return pdc

    def _upload_stream(self, filename: str, inputstream: io.FileIO, stream_len: int) -> None:
        """Upload a steam to a file on the MTP device.

        Parameters:
            filename: Name of the new file on the MTP device
            inputstream: open python file
            stream_len: length of the file to upload
        """
        try:
            object_properties = comtypes.client.CreateObject(
                types.PortableDeviceValues,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDeviceValues,
            )
            object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)
            object_properties.SetUnsignedLargeIntegerValue(WPD_OBJECT_SIZE, stream_len)
            object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, filename)
            object_properties.SetStringValue(WPD_OBJECT_NAME, filename)
            optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
            filestream, _, _ = self._content.CreateObjectWithPropertiesAndData(  # pyright: ignore[reportAttributeAccessIssue]
                object_properties,
                # p_filestream,
                optimal_transfer_size_bytes,
                ctypes.POINTER(ctypes.c_wchar_p)(),
            )
            blocksize = optimal_transfer_size_bytes.contents.value
            while True:
                block = inputstream.read(blocksize)
                if len(block) <= 0:
                    break
                string_buf = ctypes.create_string_buffer(block)
                filestream.RemoteWrite(
                    ctypes.cast(string_buf, ctypes.POINTER(ctypes.c_ubyte)),
                    len(block),
                )
            filestream.Commit(0)
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error storing stream '{filename}': {err.args[1]}")
        finally:
            object_properties = None

    def upload_file(self, filename: str, inputfilename: str) -> None:
        """Upload of a file to MTP device.

        Parameters:
            filename: Name of the new file on the MTP device
            inputfilename: Name of the file that shall be uploaded

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
            >>> if mycont: _ = mycont.remove()
            >>> cont = stor.get_path("DCIM/Camera")
            >>> name = './tests/pic.jpg'
            >>> cont.upload_file("test.jpg", name)
            >>> stor = dev[0].get_content()[0]
            >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
            >>> str(mycont)
            'PortableDeviceContent test.jpg (2)'
            >>> dev[0].close()
        """
        try:
            length = os.path.getsize(inputfilename)
            with io.FileIO(inputfilename, "r") as input_stream:
                self._upload_stream(filename, input_stream, length)
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error storing file '{filename}': {err.args[1]}")

    def _download_stream(self, outputstream: IO[bytes]) -> None:
        """Download a file from MTP device.
        The used ProtableDeviceContent instance must be a file!

        Parameters:
            outputstream: Open python file for writing
        """
        try:
            resources = self._content.Transfer()  # pyright: ignore[reportAttributeAccessIssue]
            stgm_read = ctypes.c_uint(0)
            optimal_transfer_size_bytes = ctypes.pointer(ctypes.c_ulong(0))
            optimal_transfer_size_bytes, q_filestream = resources.GetStream(
                self._object_id,
                WPD_RESOURCE_DEFAULT,
                stgm_read,
                optimal_transfer_size_bytes,
            )
            blocksize = int(optimal_transfer_size_bytes.contents.value)
            filestream = q_filestream.value
            while True:
                buf, length = filestream.RemoteRead(blocksize)
                if length == 0:
                    break
                outputstream.write(bytearray(buf[:length]))
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error getting file': {err.args[1]}")

    def download_file(self, outputfilename: str) -> None:
        """Download of a file from MTP device
        The used ProtableDeviceContent instance must be a file!

        Parameters:
            outputfilename: Name of the file the MTP file shall be written to. Any existing
                            content will be replaced.

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()
            >>> cont = stor[0].get_path(f"{stor[0].full_filename}/DCIM/Camera/IMG_20241210_160830.jpg")
            >>> name = 'picture.jpg'
            >>> cont.download_file(name)
            >>> os.remove(name)
            >>> dev[0].close()
        """
        try:
            with io.FileIO(outputfilename, "w") as output_stream:
                self._download_stream(output_stream)
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error getting file '{outputfilename}': {err.args[1]}")

    def remove(self) -> None:
        """Deletes the current directory or file.

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.win_access
            >>> dev = mtp.win_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
            >>> if mycont: _ = mycont.remove()
            >>> cont = stor.get_path("DCIM/Camera")
            >>> name = './tests/pic.jpg'
            >>> cont.upload_file("test.jpg", name)
            >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
            >>> mycont.remove()
            >>> str(mycont)
            'PortableDeviceContent test.jpg (2)'
            >>> dev[0].close()
        """
        try:
            objects_to_delete = comtypes.client.CreateObject(
                types.PortableDevicePropVariantCollection,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDevicePropVariantCollection,
            )
            pvar = port.tag_inner_PROPVARIANT()
            pvar.vt = comtypes.automation.VT_LPWSTR
            getattr(pvar, "__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001").pwszVal = ctypes.c_wchar_p(
                self._object_id
            )
            # pvar.data.pwszVal = ctypes.c_wchar_p(self._object_id)
            objects_to_delete.Add(pvar)
            errors = comtypes.client.CreateObject(
                types.PortableDevicePropVariantCollection,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDevicePropVariantCollection,
            )
            _ = self._content.Delete(WPD_DELETE_WITH_RECURSION, objects_to_delete, ctypes.pointer(errors))  # pyright: ignore[reportAttributeAccessIssue]
            # if result != 0:
            #     raise IOError(f"Error deleting directory/file '{self.full_filename}': {result}")
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error deleting directory/file '{self.full_filename}': {err.args[1]}")
        finally:
            errors = None
            objects_to_delete = None

__init__(object_id, content, device, properties=None, parent_path='')

Instance constructor

Source code in mtp/win_access.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def __init__(
    self,
    object_id: Any,
    content: "PortableDeviceContent",
    device: "PortableDevice",
    properties: Any | None = None,
    parent_path: str = "",
) -> None:
    """Instance constructor"""

    self._object_id = object_id
    self._content: "PortableDeviceContent" = content
    self._parent_path = parent_path
    self.name: str = ""
    self._plain_name: str = ""
    self.content_type: int = WPD_CONTENT_TYPE_UNDEFINED
    self.full_filename: str = ""
    self.size: int = -1
    self.date_modified: datetime.datetime = datetime.datetime.now()
    self._serialnumber: str = ""
    self._port_device = device
    self._properties = properties or content.properties()  # pyright: ignore[reportAttributeAccessIssue]
    if PortableDeviceContent._properties_to_read is None:
        # We haven't set the properties wie will read, so do it now
        PortableDeviceContent._properties_to_read = comtypes.client.CreateObject(
            types.PortableDeviceKeyCollection,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceKeyCollection
        )
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_NAME)  # pyright: ignore[reportOptionalMemberAccess]
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_ORIGINAL_FILE_NAME)  # pyright: ignore[reportOptionalMemberAccess]
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_CONTENT_TYPE)  # pyright: ignore[reportOptionalMemberAccess]
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_SIZE)  # pyright: ignore[reportOptionalMemberAccess]
        PortableDeviceContent._properties_to_read.Add(WPD_OBJECT_DATE_MODIFIED)  # pyright: ignore[reportOptionalMemberAccess]
        PortableDeviceContent._properties_to_read.Add(WPD_DEVICE_SERIAL_NUMBER)  # pyright: ignore[reportOptionalMemberAccess]
    self._get_properties()

__repr__()

String representation

Source code in mtp/win_access.py
400
401
402
def __repr__(self) -> str:
    """String representation"""
    return f"PortableDeviceContent {self.name} ({self.content_type})"

create_content(dirname)

Creates an empty directory content in this content.

Parameters:

Name Type Description Default
dirname str

Name of the directory that shall be created

required

Returns:

Type Description
PortableDeviceContent

PortableDeviceContent for the new directory

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> mycont = stor.get_path(f"{stor.full_filename}/MyMusic")
>>> if mycont: _ = mycont.remove()
>>> cont = stor.create_content("MyMusic")
>>> cont.full_filename
'Nokia 6_Nokia 6_PLEGAR1791402808\\Interner gemeinsamer Speicher\\MyMusic'
>>> dev[0].close()
Source code in mtp/win_access.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
def create_content(self, dirname: str) -> "PortableDeviceContent":
    """Creates an empty directory content in this content.

    Parameters:
        dirname: Name of the directory that shall be created

    Returns:
        PortableDeviceContent for the new directory

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> mycont = stor.get_path(f"{stor.full_filename}/MyMusic")
        >>> if mycont: _ = mycont.remove()
        >>> cont = stor.create_content("MyMusic")
        >>> cont.full_filename
        'Nokia 6_Nokia 6_PLEGAR1791402808\\\\Interner gemeinsamer Speicher\\\\MyMusic'
        >>> dev[0].close()
    """
    pdc = None
    try:
        object_properties = comtypes.client.CreateObject(
            types.PortableDeviceValues,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDeviceValues,
        )
        object_properties.SetStringValue(WPD_OBJECT_PARENT_ID, self._object_id)
        object_properties.SetStringValue(WPD_OBJECT_NAME, dirname)
        object_properties.SetStringValue(WPD_OBJECT_ORIGINAL_FILE_NAME, dirname)
        object_properties.SetGuidValue(WPD_OBJECT_CONTENT_TYPE, WPD_CONTENT_TYPE_FOLDER_GUID)
        self._content.CreateObjectWithPropertiesOnly(  # pyright: ignore[reportAttributeAccessIssue]
            object_properties, ctypes.POINTER(ctypes.c_wchar_p)()
        )
        pdc = self.get_child(dirname)
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error creating directory '{dirname}': {err.args[1]}")
    finally:
        object_properties = None
    if pdc is None:
        raise IOError(f"Error creating directory '{dirname}': Could not get conent of new directory")
    return pdc

download_file(outputfilename)

Download of a file from MTP device The used ProtableDeviceContent instance must be a file!

Parameters:

Name Type Description Default
outputfilename str

Name of the file the MTP file shall be written to. Any existing content will be replaced.

required

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()
>>> cont = stor[0].get_path(f"{stor[0].full_filename}/DCIM/Camera/IMG_20241210_160830.jpg")
>>> name = 'picture.jpg'
>>> cont.download_file(name)
>>> os.remove(name)
>>> dev[0].close()
Source code in mtp/win_access.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def download_file(self, outputfilename: str) -> None:
    """Download of a file from MTP device
    The used ProtableDeviceContent instance must be a file!

    Parameters:
        outputfilename: Name of the file the MTP file shall be written to. Any existing
                        content will be replaced.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()
        >>> cont = stor[0].get_path(f"{stor[0].full_filename}/DCIM/Camera/IMG_20241210_160830.jpg")
        >>> name = 'picture.jpg'
        >>> cont.download_file(name)
        >>> os.remove(name)
        >>> dev[0].close()
    """
    try:
        with io.FileIO(outputfilename, "w") as output_stream:
            self._download_stream(output_stream)
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error getting file '{outputfilename}': {err.args[1]}")

get_child(name)

Returns a PortableDeviceContent for one child whos name is known. The search is case sensitive.

Parameters:

Name Type Description Default
name str

The name of the file or directory to search

required

Returns:

Type Description
PortableDeviceContent | None

The PortableDeviceContent instance of the child or None if the child could not be found.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> str(list(stor.get_children())[0])
'PortableDeviceContent Pictures (1)'
>>> dev[0].close()
Source code in mtp/win_access.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def get_child(self, name: str) -> "PortableDeviceContent | None":
    """Returns a PortableDeviceContent for one child whos name is known.
    The search is case sensitive.

    Parameters:
        name: The name of the file or directory to search

    Returns:
        The PortableDeviceContent instance of the child or None if the child could not be found.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> str(list(stor.get_children())[0])
        'PortableDeviceContent Pictures (1)'
        >>> dev[0].close()
    """
    matches = [c for c in self.get_children() if c.name == name]
    return matches[0] if matches else None

get_children()

Get the child items (dirs and files) of a folder.

Returns:

Type Description
None

A Generator of PortableDeviceContent instances each representing a child entry.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> str(list(stor.get_children())[0])
'PortableDeviceContent Pictures (1)'
>>> dev[0].close()
Source code in mtp/win_access.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def get_children(self) -> collections.abc.Generator["PortableDeviceContent", None, None]:
    """Get the child items (dirs and files) of a folder.

    Returns:
        A Generator of PortableDeviceContent instances each representing a child entry.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> str(list(stor.get_children())[0])
        'PortableDeviceContent Pictures (1)'
        >>> dev[0].close()
    """
    try:
        enumobject_ids = self._content.EnumObjects(  # pyright: ignore[reportAttributeAccessIssue]
            ctypes.c_ulong(0),
            self._object_id,
            ctypes.POINTER(port.IPortableDeviceValues)(),
        )
        while True:
            num_fetched = ctypes.pointer(ctypes.c_ulong(0))
            # Always load only one entry
            object_id_array = enumobject_ids.Next(
                1,
                num_fetched,
            )
            if num_fetched.contents.value == 0:
                break
            curobject_id = str(object_id_array[0])
            value = PortableDeviceContent(curobject_id, self._content, self._port_device, self._properties, self.full_filename)
            yield value
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error getting child item from '{self.full_filename}': {err.args[1]}")

get_path(path)

Returns a PortableDeviceContent for a child who's path in the tree is known. The path can be fully qualified or starting from the current content.

Parameters:

Name Type Description Default
path str

The pathname to the child.

required

Returns:

Type Description
PortableDeviceContent | None

The PortableDeviceContent instance of the child or None if the child could not be found.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> str(stor.get_path(f"{stor.full_filename}/DCIM"))
'PortableDeviceContent DCIM (1)'
>>> str(stor.get_path(f"DCIM"))
'PortableDeviceContent DCIM (1)'
>>> dev[0].close()
Source code in mtp/win_access.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
def get_path(self, path: str) -> "PortableDeviceContent | None":
    """Returns a PortableDeviceContent for a child who's path in the tree is known.
    The path can be fully qualified or starting from the current content.

    Parameters:
        path: The pathname to the child.

    Returns:
        The PortableDeviceContent instance of the child or None if the child could not be found.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> str(stor.get_path(f"{stor.full_filename}/DCIM"))
        'PortableDeviceContent DCIM (1)'
        >>> str(stor.get_path(f"DCIM"))
        'PortableDeviceContent DCIM (1)'
        >>> dev[0].close()
    """
    name = path.replace("/", os.path.sep)
    start = name.split(os.sep, 1)[0]
    if start == self._port_device.devicename:
        return get_content_from_device_path(self._port_device, name)
    if start == self.name:
        name = name.split(os.sep, 1)[1]
    cur: "PortableDeviceContent | None" = self
    for part in name.split(os.path.sep):
        if not cur:
            return None
        cur = cur.get_child(part)
    return cur

remove()

Deletes the current directory or file.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> mycont = stor.get_path("DCIM/Camera/test.jpg")
>>> if mycont: _ = mycont.remove()
>>> cont = stor.get_path("DCIM/Camera")
>>> name = './tests/pic.jpg'
>>> cont.upload_file("test.jpg", name)
>>> mycont = stor.get_path("DCIM/Camera/test.jpg")
>>> mycont.remove()
>>> str(mycont)
'PortableDeviceContent test.jpg (2)'
>>> dev[0].close()
Source code in mtp/win_access.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
def remove(self) -> None:
    """Deletes the current directory or file.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
        >>> if mycont: _ = mycont.remove()
        >>> cont = stor.get_path("DCIM/Camera")
        >>> name = './tests/pic.jpg'
        >>> cont.upload_file("test.jpg", name)
        >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
        >>> mycont.remove()
        >>> str(mycont)
        'PortableDeviceContent test.jpg (2)'
        >>> dev[0].close()
    """
    try:
        objects_to_delete = comtypes.client.CreateObject(
            types.PortableDevicePropVariantCollection,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDevicePropVariantCollection,
        )
        pvar = port.tag_inner_PROPVARIANT()
        pvar.vt = comtypes.automation.VT_LPWSTR
        getattr(pvar, "__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001").pwszVal = ctypes.c_wchar_p(
            self._object_id
        )
        # pvar.data.pwszVal = ctypes.c_wchar_p(self._object_id)
        objects_to_delete.Add(pvar)
        errors = comtypes.client.CreateObject(
            types.PortableDevicePropVariantCollection,
            clsctx=comtypes.CLSCTX_INPROC_SERVER,
            interface=port.IPortableDevicePropVariantCollection,
        )
        _ = self._content.Delete(WPD_DELETE_WITH_RECURSION, objects_to_delete, ctypes.pointer(errors))  # pyright: ignore[reportAttributeAccessIssue]
        # if result != 0:
        #     raise IOError(f"Error deleting directory/file '{self.full_filename}': {result}")
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error deleting directory/file '{self.full_filename}': {err.args[1]}")
    finally:
        errors = None
        objects_to_delete = None

upload_file(filename, inputfilename)

Upload of a file to MTP device.

Parameters:

Name Type Description Default
filename str

Name of the new file on the MTP device

required
inputfilename str

Name of the file that shall be uploaded

required

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> mycont = stor.get_path("DCIM/Camera/test.jpg")
>>> if mycont: _ = mycont.remove()
>>> cont = stor.get_path("DCIM/Camera")
>>> name = './tests/pic.jpg'
>>> cont.upload_file("test.jpg", name)
>>> stor = dev[0].get_content()[0]
>>> mycont = stor.get_path("DCIM/Camera/test.jpg")
>>> str(mycont)
'PortableDeviceContent test.jpg (2)'
>>> dev[0].close()
Source code in mtp/win_access.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def upload_file(self, filename: str, inputfilename: str) -> None:
    """Upload of a file to MTP device.

    Parameters:
        filename: Name of the new file on the MTP device
        inputfilename: Name of the file that shall be uploaded

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
        >>> if mycont: _ = mycont.remove()
        >>> cont = stor.get_path("DCIM/Camera")
        >>> name = './tests/pic.jpg'
        >>> cont.upload_file("test.jpg", name)
        >>> stor = dev[0].get_content()[0]
        >>> mycont = stor.get_path("DCIM/Camera/test.jpg")
        >>> str(mycont)
        'PortableDeviceContent test.jpg (2)'
        >>> dev[0].close()
    """
    try:
        length = os.path.getsize(inputfilename)
        with io.FileIO(inputfilename, "r") as input_stream:
            self._upload_stream(filename, input_stream, length)
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error storing file '{filename}': {err.args[1]}")

get_content_from_device_path(dev, path)

Get the content of a path.

Parameters:

Name Type Description Default
dev PortableDevice

The instance of PortableDevice where the path is searched

required
path str

The pathname of the file or directory

required

Returns:

Type Description
PortableDeviceContent | None

An instance of PortableDeviceContent if the path is an existing file or directory else None is returned.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
>>> cont = mtp.win_access.get_content_from_device_path(dev[0], n)
>>> str(cont)
'PortableDeviceContent Camera (1)'
>>> dev[0].close()
Source code in mtp/win_access.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
def get_content_from_device_path(dev: PortableDevice, path: str) -> PortableDeviceContent | None:
    """Get the content of a path.

    Parameters:
        dev: The instance of PortableDevice where the path is searched
        path: The pathname of the file or directory

    Returns:
        An instance of PortableDeviceContent if the path is an existing file or directory
            else None is returned.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        >>> cont = mtp.win_access.get_content_from_device_path(dev[0], n)
        >>> str(cont)
        'PortableDeviceContent Camera (1)'
        >>> dev[0].close()
    """
    path = path.replace("\\", os.path.sep).replace("/", os.path.sep)
    path_parts = path.split(os.path.sep)
    if len(path_parts) < 2:
        raise IOError("get_content_from_device_path needs a devicename and a storage as paramter")
    if path_parts[0] == dev.devicename:
        try:
            cont: PortableDeviceContent | None = None
            for entry in dev.get_content():
                if entry.name == path_parts[1]:
                    cont = entry
                    break
            if cont is None:
                return None
            for part in path_parts[2:]:
                cont = cont.get_child(part)
                if cont is None:
                    return None
            return cont
        except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
            raise IOError(f"Error reading directory '{path}': {err.args[1]}")
    return None

get_portable_devices()

Get all attached portable devices.

Returns:

Type Description
list[PortableDevice]

A list of PortableDevice one for each found MTP device. The list is empty if no device was found.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> devs = mtp.win_access.get_portable_devices()
>>> len(devs) == 1
True
Source code in mtp/win_access.py
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
def get_portable_devices() -> list[PortableDevice]:
    """Get all attached portable devices.

    Returns:
        A list of PortableDevice one for each found MTP device. The list is empty if no device
            was found.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> devs = mtp.win_access.get_portable_devices()
        >>> len(devs) == 1
        True
    """
    global DEVICE_MANAGER

    try:
        if DEVICE_MANAGER is None:
            comtypes.CoInitialize()
            DEVICE_MANAGER = comtypes.client.CreateObject(
                port.PortableDeviceManager,
                clsctx=comtypes.CLSCTX_INPROC_SERVER,
                interface=port.IPortableDeviceManager
            )
        if DEVICE_MANAGER is None:
            raise IOError("Error initialising Windows PortableDeviceManager")
        pnp_device_id_count = ctypes.pointer(ctypes.c_ulong(0))
        DEVICE_MANAGER.GetDevices(ctypes.POINTER(ctypes.c_wchar_p)(), pnp_device_id_count)
        if pnp_device_id_count.contents.value == 0:
            return []
        pnp_device_ids = (ctypes.c_wchar_p * pnp_device_id_count.contents.value)()
        DEVICE_MANAGER.GetDevices(
            ctypes.cast(pnp_device_ids, ctypes.POINTER(ctypes.c_wchar_p)),
            pnp_device_id_count,
        )
        return [PortableDevice(cur_id) for cur_id in pnp_device_ids if cur_id is not None]
    except comtypes.COMError as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error getting list of devices: {err.args[1]}")

makedirs(dev, path)

Creates the directories in path on the MTP device if they don't exist.

Parameters:

Name Type Description Default
dev PortableDevice

Portable device to create the dirs on

required
path str

pathname of the dir to create. Any directories in path that don't exist will be created automatically.

required

Returns:

Type Description
PortableDeviceContent

A PortableDeviceContent instance for the last directory in path.

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
>>> cont = mtp.win_access.makedirs(dev[0], n)
>>> str(cont)
'PortableDeviceContent Test (1)'
>>> cont.remove()
>>> dev[0].close()
Source code in mtp/win_access.py
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
def makedirs(dev: PortableDevice, path: str) -> PortableDeviceContent:
    """Creates the directories in path on the MTP device if they don't exist.

    Parameters:
        dev: Portable device to create the dirs on
        path: pathname of the dir to create. Any directories in path that don't exist
            will be created automatically.

    Returns:
        A PortableDeviceContent instance for the last directory in path.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
        >>> cont = mtp.win_access.makedirs(dev[0], n)
        >>> str(cont)
        'PortableDeviceContent Test (1)'
        >>> cont.remove()
        >>> dev[0].close()
    """
    try:
        content = dev.get_content()[0]
        path = path.replace("\\", os.path.sep).replace("/", os.path.sep)
        parts = path.split(os.path.sep)
        path_int = parts[0]
        for dirname in parts[1:]:
            if dirname == "":
                continue
            path_int = os.path.join(path_int, dirname)
            ziel_content = get_content_from_device_path(dev, path_int)
            if ziel_content is None:
                ziel_content = content.create_content(dirname)
            content = ziel_content
        return content
    except (comtypes.COMError, ImportError) as err:  # pyright: ignore[reportAttributeAccessIssue]
        raise IOError(f"Error creating directory '{path}': {err.args[1]}")

walk(dev, path, callback=None, error_callback=None)

Iterates ower all files in a tree just like os.walk

Parameters:

Name Type Description Default
dev PortableDevice

Portable device to iterate in

required
path str

path from witch to iterate

required
callback Callable[[str], bool] | None

when given, a function that takes one argument (the selected file) and returns a boolean. If the returned value is false, walk will cancel an return empty list. the callback is usefull to show for example a progress because reading thousands of file from one MTP directory lasts very long.

None
error_callback Callable[[str], bool] | None

when given, a function that takes one argument (the errormessage) and returns a boolean. If the returned value is false, walk will cancel and return empty list.

None

Returns:

Type Description
Generator[tuple[str, list[PortableDeviceContent], list[PortableDeviceContent]],]

A tuple with this content: A string with the root directory A list of PortableDeviceContent for the directories in the directory A list of PortableDeviceContent for the files in the directory

Raises:

Type Description
IOError

If something went wrong

Examples:

>>> import mtp.win_access
>>> dev = mtp.win_access.get_portable_devices()
>>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
>>> for r, d, f in mtp.win_access.walk(dev[0], n):
...     for f1 in f:
...             print(f1.name)
...
IMG_20241210_160830.jpg
IMG_20241210_160833.jpg
IMG_20241210_161150.jpg
test.jpg
>>> dev[0].close()
Source code in mtp/win_access.py
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def walk(
    dev: PortableDevice,
    path: str,
    callback: Callable[[str], bool] | None = None,
    error_callback: Callable[[str], bool] | None = None,
) -> collections.abc.Generator[tuple[str, list[PortableDeviceContent], list[PortableDeviceContent]],]:
    """Iterates ower all files in a tree just like os.walk

    Parameters:
        dev: Portable device to iterate in
        path: path from witch to iterate
        callback: when given, a function that takes one argument (the selected file) and returns
                a boolean. If the returned value is false, walk will cancel an return empty
                list.
                the callback is usefull to show for example a progress because reading thousands
                of file from one MTP directory lasts very long.
        error_callback: when given, a function that takes one argument (the errormessage) and returns
                a boolean. If the returned value is false, walk will cancel and return empty
                list.

    Returns:
        A tuple with this content:
            A string with the root directory
            A list of PortableDeviceContent for the directories  in the directory
            A list of PortableDeviceContent for the files in the directory

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.win_access
        >>> dev = mtp.win_access.get_portable_devices()
        >>> n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        >>> for r, d, f in mtp.win_access.walk(dev[0], n):
        ...     for f1 in f:
        ...             print(f1.name)
        ...
        IMG_20241210_160830.jpg
        IMG_20241210_160833.jpg
        IMG_20241210_161150.jpg
        test.jpg
        >>> dev[0].close()
    """
    if not (cont := get_content_from_device_path(dev, path)):
        return
    cont.full_filename = path
    walk_cont: list[PortableDeviceContent] = [cont]
    while walk_cont:
        cont = walk_cont[0]
        del walk_cont[0]
        directories: list[PortableDeviceContent] = []
        files: list[PortableDeviceContent] = []
        try:
            for child in cont.get_children():
                if child.content_type in [
                    WPD_CONTENT_TYPE_STORAGE,
                    WPD_CONTENT_TYPE_DIRECTORY,
                ]:
                    directories.append(child)
                elif child.content_type == WPD_CONTENT_TYPE_FILE:
                    files.append(child)
                if callback and not callback(child.full_filename):
                    directories = []
                    files = []
                    return
            yield cont.full_filename, sorted(directories, key=lambda ent: ent.full_filename), sorted(
                files, key=lambda ent: ent.full_filename
            )
        except Exception as err:
            if error_callback is not None:
                if not error_callback(str(err)):
                    directories = []
                    files = []
                    return
        walk_cont.extend(directories)