Skip to content

linux_access

linux_access Documentation

A module to access Mobile Devices from UNIX via USB connection. After connecting to gnome desktop the devices can be found under: /run/user/1000/gvfs/ in the normal file system. If on an other desktop environment, for example KDE, then any process that uses libmtp will be killed and this module will access libmtp.

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
    • Linux (GNOME and KDE)

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.linux_access
>>> devs = mtp.linux_access.get_portable_devices()
>>> len(devs) >= 1
True
>>> str(devs[0])[:16]
'PortableDevice: '
>>> 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 str

Name of the MTP device

description str

Description for the device

serialnumber str

Serialnumber of the device

devicename str

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

Raises:

Type Description
IOError

If something went wrong

Source code in mtp/linux_access.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
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
    """

    def __init__(
        self, device: "str | ctypes._Pointer[pylibmtp.LIBMTP_RawDevice]"  # pyright: ignore[reportPrivateUsage]
    ) -> None:
        """Init the class.

        Parameters:
           device: Linux path to the device on Gnome or a libmtp device pointer on KDE
        """
        self.description: str = "Unknown"
        self.name: str = "Unknown"
        self.serialnumber: str = "Unknown"
        self.device_start_part: str
        self.devicename: str
        if type(device) == str:
            self._device: str = device
            if "=" in device:
                self.device_start_part, self.devicename = device.split("=", 1)
                self.device_start_part += "="
            else:
                self.device_start_part = ""
                self.devicename = device
            if "_" in self.devicename:
                parts: list[str] = self.devicename.split("_")
                try:
                    self.name = parts[0]
                    self.description = parts[-2]
                    self.serialnumber = parts[-1]
                except IndexError:
                    pass
        else:
            # We do the killing of the processes that use libmtp just bevor
            # we use libmtp because so the chances that any other programm
            # greps libmtp back is very small
            if _libmtp is None:
                _init_libmtp()
            self.libmntp_device: pylibmtp.MTP = pylibmtp.MTP(device)
            self.libmntp_device.connect()
            self.name = self.libmntp_device.get_devicename()
            self.description = self.libmntp_device.get_modelname()
            if self.name == "":
                self.name = self.description
            self.serialnumber = self.libmntp_device.get_serialnumber()
            self.devicename = f"{self.name}_{self.description}_{self.serialnumber}"

    def close(self) -> None:
        """Close the connection to the device. This must be called when the device is no more needed."""
        if not _gvfs_found:
            self.libmntp_device.disconnect()

    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.linux_access
            >>> dev = mtp.linux_access.get_portable_devices()
            >>> stor = dev[0].get_content()
            >>> len(stor)
            2
            >>> str(stor[0])[:31]
            'PortableDeviceContent Interner '
            >>> dev[0].close()
        """
        ret_objs: list["PortableDeviceContent"] = []
        if _gvfs_found:
            try:
                for entry in os.listdir(os.path.join(_gvfs_search_path, self._device)):
                    full_name = os.path.join(self.devicename, entry)
                    ret_objs.append(PortableDeviceContent(self, full_name, 0, 0, WPD_CONTENT_TYPE_STORAGE))
            except OSError as err:
                raise IOError(f"Can't access {self.devicename}.") from err
        else:
            try:
                for entry in self.libmntp_device.get_storage():
                    full_name = os.path.join(self.devicename, entry[0])
                    pdc: PortableDeviceContent = PortableDeviceContent(
                        port_device=self,
                        dirpath=full_name,
                        storage_id=entry[1],
                        entry_id=pylibmtp.LIBMTP_FILES_AND_FOLDERS_ROOT,
                        typ=WPD_CONTENT_TYPE_STORAGE,
                    )
                    ret_objs.append(pdc)
            except pylibmtp.CommandFailed as err:
                raise IOError(f"Can't access {self.devicename}.") from err
        ret_objs.sort(key=lambda entry: entry.name)
        return ret_objs

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

__init__(device)

Init the class.

Parameters:

Name Type Description Default
device str | _Pointer[LIBMTP_RawDevice]

Linux path to the device on Gnome or a libmtp device pointer on KDE

required
Source code in mtp/linux_access.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def __init__(
    self, device: "str | ctypes._Pointer[pylibmtp.LIBMTP_RawDevice]"  # pyright: ignore[reportPrivateUsage]
) -> None:
    """Init the class.

    Parameters:
       device: Linux path to the device on Gnome or a libmtp device pointer on KDE
    """
    self.description: str = "Unknown"
    self.name: str = "Unknown"
    self.serialnumber: str = "Unknown"
    self.device_start_part: str
    self.devicename: str
    if type(device) == str:
        self._device: str = device
        if "=" in device:
            self.device_start_part, self.devicename = device.split("=", 1)
            self.device_start_part += "="
        else:
            self.device_start_part = ""
            self.devicename = device
        if "_" in self.devicename:
            parts: list[str] = self.devicename.split("_")
            try:
                self.name = parts[0]
                self.description = parts[-2]
                self.serialnumber = parts[-1]
            except IndexError:
                pass
    else:
        # We do the killing of the processes that use libmtp just bevor
        # we use libmtp because so the chances that any other programm
        # greps libmtp back is very small
        if _libmtp is None:
            _init_libmtp()
        self.libmntp_device: pylibmtp.MTP = pylibmtp.MTP(device)
        self.libmntp_device.connect()
        self.name = self.libmntp_device.get_devicename()
        self.description = self.libmntp_device.get_modelname()
        if self.name == "":
            self.name = self.description
        self.serialnumber = self.libmntp_device.get_serialnumber()
        self.devicename = f"{self.name}_{self.description}_{self.serialnumber}"

close()

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

Source code in mtp/linux_access.py
182
183
184
185
def close(self) -> None:
    """Close the connection to the device. This must be called when the device is no more needed."""
    if not _gvfs_found:
        self.libmntp_device.disconnect()

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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> stor = dev[0].get_content()
>>> len(stor)
2
>>> str(stor[0])[:31]
'PortableDeviceContent Interner '
>>> dev[0].close()
Source code in mtp/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> stor = dev[0].get_content()
        >>> len(stor)
        2
        >>> str(stor[0])[:31]
        'PortableDeviceContent Interner '
        >>> dev[0].close()
    """
    ret_objs: list["PortableDeviceContent"] = []
    if _gvfs_found:
        try:
            for entry in os.listdir(os.path.join(_gvfs_search_path, self._device)):
                full_name = os.path.join(self.devicename, entry)
                ret_objs.append(PortableDeviceContent(self, full_name, 0, 0, WPD_CONTENT_TYPE_STORAGE))
        except OSError as err:
            raise IOError(f"Can't access {self.devicename}.") from err
    else:
        try:
            for entry in self.libmntp_device.get_storage():
                full_name = os.path.join(self.devicename, entry[0])
                pdc: PortableDeviceContent = PortableDeviceContent(
                    port_device=self,
                    dirpath=full_name,
                    storage_id=entry[1],
                    entry_id=pylibmtp.LIBMTP_FILES_AND_FOLDERS_ROOT,
                    typ=WPD_CONTENT_TYPE_STORAGE,
                )
                ret_objs.append(pdc)
        except pylibmtp.CommandFailed as err:
            raise IOError(f"Can't access {self.devicename}.") from err
    ret_objs.sort(key=lambda entry: entry.name)
    return ret_objs

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/linux_access.py
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
class PortableDeviceContent:  # pylint: disable=too-many-instance-attributes
    """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
    """

    def __init__(
        self,
        port_device: PortableDevice,
        dirpath: str,
        storage_id: int,
        entry_id: int,
        typ: int,
        size: int = 0,
        date_modified: int = 0,
    ) -> None:
        """Instance constructor"""

        self._port_device: PortableDevice = port_device
        self.full_filename: str = dirpath
        self.name: str = os.path.basename(dirpath)
        self.storage_id: int = storage_id
        self.entry_id: int = entry_id
        self.content_type: int = typ
        self.size: int = -1
        self.date_modified: datetime.datetime = datetime.datetime.now()
        if typ == WPD_CONTENT_TYPE_FILE:
            if _gvfs_found:
                try:
                    full_filename = os.path.join(
                        _gvfs_search_path, port_device.device_start_part + dirpath 
                    ) 
                    self.size = os.path.getsize(full_filename)
                    self.date_modified = datetime.datetime.fromtimestamp(os.path.getmtime(full_filename))
                except OSError:
                    self.content_type = WPD_CONTENT_TYPE_STORAGE
            else:
                self.size = size
                self.date_modified = datetime.datetime.fromtimestamp(date_modified)
        elif typ == WPD_CONTENT_TYPE_DEVICE:
            self.full_filename = port_device.devicename

    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.linux_access
            >>> dev = mtp.linux_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> str(list(stor.get_children())[0])
            'PortableDeviceContent Pictures (1)'
            >>> dev[0].close()
        """
        if _gvfs_found:
            full_filename: str = os.path.join(
                _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
            )
            if not os.path.isdir(full_filename):
                return
            for entry in os.listdir(full_filename):
                full_name = os.path.join(self.full_filename, entry)
                yield PortableDeviceContent(
                    self._port_device,
                    full_name,
                    1,
                    0,
                    (
                        WPD_CONTENT_TYPE_DIRECTORY
                        if os.path.isdir(os.path.join(full_filename, entry))
                        else WPD_CONTENT_TYPE_FILE
                    ),
                )
        else:
            if _libmtp is None:
                return
            for entry in self._port_device.libmntp_device.get_files_and_folder(  
                self.storage_id, self.entry_id
            ):
                type: Literal[1, 2] = (
                    WPD_CONTENT_TYPE_DIRECTORY
                    if entry.filetype == pylibmtp.LIBMTP_Filetype["FOLDER"].value  # pyright: ignore[reportAny]
                    else WPD_CONTENT_TYPE_FILE
                )
                yield PortableDeviceContent(
                    self._port_device,
                    os.path.join(self.full_filename, entry.filename.decode("utf-8")),  # pyright: ignore[reportAny]
                    self.storage_id,
                    entry.item_id,  # pyright: ignore[reportAny]
                    type,
                    entry.filesize,  # pyright: ignore[reportAny]
                    entry.modificationdate,  # pyright: ignore[reportAny]
                )

    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.linux_access
            >>> dev = mtp.linux_access.get_portable_devices()
            >>> stor = dev[0].get_content()[0]
            >>> str(stor.get_child("DCIM"))
            'PortableDeviceContent DCIM (1)'
            >>> dev[0].close()
        """
        if _gvfs_found:
            fullname = os.path.join(
                _gvfs_search_path, self._port_device.device_start_part + self.full_filename, name  
            )
            if not os.path.exists(fullname):
                return None
            return PortableDeviceContent(
                self._port_device,
                os.path.join(self.full_filename, name),
                1,
                1,
                (WPD_CONTENT_TYPE_DIRECTORY if os.path.isdir(fullname) else WPD_CONTENT_TYPE_FILE),
            )
        else:
            if _libmtp is None:
                return
            for entry in self._port_device.libmntp_device.get_files_and_folder(  
                self.storage_id, self.entry_id
            ):
                entry_filename = entry.filename.decode("UTF-8")  # pyright: ignore[reportAny]
                if entry_filename != name:
                    continue
                # Ok found, so do a direct return
                type: Literal[1, 2] = (
                    WPD_CONTENT_TYPE_DIRECTORY
                    if entry.filetype == pylibmtp.LIBMTP_Filetype["FOLDER"].value  # pyright: ignore[reportAny]
                    else WPD_CONTENT_TYPE_FILE
                )
                return PortableDeviceContent(
                    self._port_device,
                    os.path.join(self.full_filename, entry_filename),  # pyright: ignore[reportAny]
                    self.storage_id,
                    entry.item_id,  # pyright: ignore[reportAny]
                    type,
                    entry.filesize,  # pyright: ignore[reportAny]
                    entry.modificationdate,  # pyright: ignore[reportAny]
                )
            return 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.linux_access
            >>> dev = mtp.linux_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()
        """
        path = path.replace("\\", os.path.sep)
        start = path.split(os.sep, 1)[0]
        if start == self._port_device.devicename:
            return get_content_from_device_path(self._port_device, path)
        if start == self.name:
            path = path.split(os.sep, 1)[1]
        # Difference between gvfs and libmtp
        if _gvfs_found:
            full_filename = os.path.join(
                _gvfs_search_path,
                self._port_device.device_start_part + self.full_filename, 
                path, 
            )
            if not os.path.exists(full_filename):
                return None
            return PortableDeviceContent(
                self._port_device,
                os.path.join(self.full_filename, path),
                1,
                1,
                (WPD_CONTENT_TYPE_DIRECTORY if os.path.isdir(full_filename) else WPD_CONTENT_TYPE_FILE),
            )
        else:
            cur: "PortableDeviceContent | None" = self
            for part in path.split(os.path.sep):
                if not cur:
                    return None
                cur = cur.get_child(part)
            return cur

    @override
    def __repr__(self) -> str:
        """ """
        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.linux_access
            >>> dev = mtp.linux_access.get_portable_devices()
            >>> stor = dev[0].get_content()
            >>> mycont = stor[0].get_path(f"{stor[0].full_filename}/MyMusic")
            >>> if mycont: _ = mycont.remove()
            >>> cont = stor[0].create_content("MyMusic")
            >>> str(cont)
            'PortableDeviceContent MyMusic (1)'
            >>> dev[0].close()
        """
        fullname = os.path.join(self.full_filename, dirname)
        if _gvfs_found:
            full_filename = os.path.join(
                _gvfs_search_path, self._port_device.device_start_part + fullname  
            )
            if os.path.exists(full_filename):
                raise IOError(f"Directory '{fullname}' allready exists")
            os.mkdir(full_filename)
            pdc = PortableDeviceContent(self._port_device, fullname, 0, 0, WPD_CONTENT_TYPE_DIRECTORY)
        else:
            try:
                id = self._port_device.libmntp_device.create_folder(  
                    dirname, self.entry_id, self.storage_id
                )
                pdc = PortableDeviceContent(
                    self._port_device, fullname, self.storage_id, id, WPD_CONTENT_TYPE_DIRECTORY
                )
            except Exception:
                raise IOError(f"Error creating directory '{fullname}'")
        return pdc

    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.linux_access
            >>> dev = mtp.linux_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()
        """
        if _gvfs_found:
            full_filename = os.path.join(
                _gvfs_search_path,
                self._port_device.device_start_part + self.full_filename,  
                filename,
            )
            try:
                _ = shutil.copyfile(inputfilename, full_filename)
            except OSError:
                # Ok can't copy with shutil on older Gnomes (for example Zorin). si we use gio
                gio_full_filename = "mtp://" + full_filename.split("=", 1)[1]
                try:
                    _ = subprocess.check_output(
                        f'gio copy "{inputfilename}" "{gio_full_filename}"',
                        shell=True,
                        stderr=subprocess.STDOUT,
                    )
                except subprocess.CalledProcessError as err:
                    raise IOError(
                        f"Error copying file '{inputfilename}' to '{gio_full_filename}': {urllib.parse.unquote(err.output.decode('utf-8'))}"  # pyright: ignore[reportAny]
                    ) from err
            # shutil.copy(inputfilename, full_filename)
        else:
            _ = self._port_device.libmntp_device.send_file_from_file(  
                inputfilename, filename, self.storage_id, self.entry_id
            )

    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.linux_access
            >>> dev = mtp.linux_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()
        """
        if _gvfs_found:
            full_filename = os.path.join(
                _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
            )
            _ = shutil.copy2(full_filename, outputfilename)
        else:
            self._port_device.libmntp_device.get_file_to_file(  
                self.entry_id, outputfilename
            )

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

        Exceptions:
            IOError: If something went wrong

        Examples:
            >>> import mtp.linux_access
            >>> dev = mtp.linux_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()
        """
        if _gvfs_found:
            full_name = os.path.join(
                _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
            )
            if not os.path.exists(full_name):
                return
            if self.content_type == WPD_CONTENT_TYPE_FILE:
                os.remove(full_name)
            else:
                shutil.rmtree(full_name)
        else:
            self._port_device.libmntp_device.delete_object(self.entry_id)  

__init__(port_device, dirpath, storage_id, entry_id, typ, size=0, date_modified=0)

Instance constructor

Source code in mtp/linux_access.py
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
def __init__(
    self,
    port_device: PortableDevice,
    dirpath: str,
    storage_id: int,
    entry_id: int,
    typ: int,
    size: int = 0,
    date_modified: int = 0,
) -> None:
    """Instance constructor"""

    self._port_device: PortableDevice = port_device
    self.full_filename: str = dirpath
    self.name: str = os.path.basename(dirpath)
    self.storage_id: int = storage_id
    self.entry_id: int = entry_id
    self.content_type: int = typ
    self.size: int = -1
    self.date_modified: datetime.datetime = datetime.datetime.now()
    if typ == WPD_CONTENT_TYPE_FILE:
        if _gvfs_found:
            try:
                full_filename = os.path.join(
                    _gvfs_search_path, port_device.device_start_part + dirpath 
                ) 
                self.size = os.path.getsize(full_filename)
                self.date_modified = datetime.datetime.fromtimestamp(os.path.getmtime(full_filename))
            except OSError:
                self.content_type = WPD_CONTENT_TYPE_STORAGE
        else:
            self.size = size
            self.date_modified = datetime.datetime.fromtimestamp(date_modified)
    elif typ == WPD_CONTENT_TYPE_DEVICE:
        self.full_filename = port_device.devicename

__repr__()

Source code in mtp/linux_access.py
473
474
475
476
@override
def __repr__(self) -> str:
    """ """
    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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> stor = dev[0].get_content()
>>> mycont = stor[0].get_path(f"{stor[0].full_filename}/MyMusic")
>>> if mycont: _ = mycont.remove()
>>> cont = stor[0].create_content("MyMusic")
>>> str(cont)
'PortableDeviceContent MyMusic (1)'
>>> dev[0].close()
Source code in mtp/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> stor = dev[0].get_content()
        >>> mycont = stor[0].get_path(f"{stor[0].full_filename}/MyMusic")
        >>> if mycont: _ = mycont.remove()
        >>> cont = stor[0].create_content("MyMusic")
        >>> str(cont)
        'PortableDeviceContent MyMusic (1)'
        >>> dev[0].close()
    """
    fullname = os.path.join(self.full_filename, dirname)
    if _gvfs_found:
        full_filename = os.path.join(
            _gvfs_search_path, self._port_device.device_start_part + fullname  
        )
        if os.path.exists(full_filename):
            raise IOError(f"Directory '{fullname}' allready exists")
        os.mkdir(full_filename)
        pdc = PortableDeviceContent(self._port_device, fullname, 0, 0, WPD_CONTENT_TYPE_DIRECTORY)
    else:
        try:
            id = self._port_device.libmntp_device.create_folder(  
                dirname, self.entry_id, self.storage_id
            )
            pdc = PortableDeviceContent(
                self._port_device, fullname, self.storage_id, id, WPD_CONTENT_TYPE_DIRECTORY
            )
        except Exception:
            raise IOError(f"Error creating directory '{fullname}'")
    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.linux_access
>>> dev = mtp.linux_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/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_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()
    """
    if _gvfs_found:
        full_filename = os.path.join(
            _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
        )
        _ = shutil.copy2(full_filename, outputfilename)
    else:
        self._port_device.libmntp_device.get_file_to_file(  
            self.entry_id, outputfilename
        )

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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> stor = dev[0].get_content()[0]
>>> str(stor.get_child("DCIM"))
'PortableDeviceContent DCIM (1)'
>>> dev[0].close()
Source code in mtp/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> str(stor.get_child("DCIM"))
        'PortableDeviceContent DCIM (1)'
        >>> dev[0].close()
    """
    if _gvfs_found:
        fullname = os.path.join(
            _gvfs_search_path, self._port_device.device_start_part + self.full_filename, name  
        )
        if not os.path.exists(fullname):
            return None
        return PortableDeviceContent(
            self._port_device,
            os.path.join(self.full_filename, name),
            1,
            1,
            (WPD_CONTENT_TYPE_DIRECTORY if os.path.isdir(fullname) else WPD_CONTENT_TYPE_FILE),
        )
    else:
        if _libmtp is None:
            return
        for entry in self._port_device.libmntp_device.get_files_and_folder(  
            self.storage_id, self.entry_id
        ):
            entry_filename = entry.filename.decode("UTF-8")  # pyright: ignore[reportAny]
            if entry_filename != name:
                continue
            # Ok found, so do a direct return
            type: Literal[1, 2] = (
                WPD_CONTENT_TYPE_DIRECTORY
                if entry.filetype == pylibmtp.LIBMTP_Filetype["FOLDER"].value  # pyright: ignore[reportAny]
                else WPD_CONTENT_TYPE_FILE
            )
            return PortableDeviceContent(
                self._port_device,
                os.path.join(self.full_filename, entry_filename),  # pyright: ignore[reportAny]
                self.storage_id,
                entry.item_id,  # pyright: ignore[reportAny]
                type,
                entry.filesize,  # pyright: ignore[reportAny]
                entry.modificationdate,  # pyright: ignore[reportAny]
            )
        return 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.linux_access
>>> dev = mtp.linux_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/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> stor = dev[0].get_content()[0]
        >>> str(list(stor.get_children())[0])
        'PortableDeviceContent Pictures (1)'
        >>> dev[0].close()
    """
    if _gvfs_found:
        full_filename: str = os.path.join(
            _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
        )
        if not os.path.isdir(full_filename):
            return
        for entry in os.listdir(full_filename):
            full_name = os.path.join(self.full_filename, entry)
            yield PortableDeviceContent(
                self._port_device,
                full_name,
                1,
                0,
                (
                    WPD_CONTENT_TYPE_DIRECTORY
                    if os.path.isdir(os.path.join(full_filename, entry))
                    else WPD_CONTENT_TYPE_FILE
                ),
            )
    else:
        if _libmtp is None:
            return
        for entry in self._port_device.libmntp_device.get_files_and_folder(  
            self.storage_id, self.entry_id
        ):
            type: Literal[1, 2] = (
                WPD_CONTENT_TYPE_DIRECTORY
                if entry.filetype == pylibmtp.LIBMTP_Filetype["FOLDER"].value  # pyright: ignore[reportAny]
                else WPD_CONTENT_TYPE_FILE
            )
            yield PortableDeviceContent(
                self._port_device,
                os.path.join(self.full_filename, entry.filename.decode("utf-8")),  # pyright: ignore[reportAny]
                self.storage_id,
                entry.item_id,  # pyright: ignore[reportAny]
                type,
                entry.filesize,  # pyright: ignore[reportAny]
                entry.modificationdate,  # pyright: ignore[reportAny]
            )

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.linux_access
>>> dev = mtp.linux_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/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_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()
    """
    path = path.replace("\\", os.path.sep)
    start = path.split(os.sep, 1)[0]
    if start == self._port_device.devicename:
        return get_content_from_device_path(self._port_device, path)
    if start == self.name:
        path = path.split(os.sep, 1)[1]
    # Difference between gvfs and libmtp
    if _gvfs_found:
        full_filename = os.path.join(
            _gvfs_search_path,
            self._port_device.device_start_part + self.full_filename, 
            path, 
        )
        if not os.path.exists(full_filename):
            return None
        return PortableDeviceContent(
            self._port_device,
            os.path.join(self.full_filename, path),
            1,
            1,
            (WPD_CONTENT_TYPE_DIRECTORY if os.path.isdir(full_filename) else WPD_CONTENT_TYPE_FILE),
        )
    else:
        cur: "PortableDeviceContent | None" = self
        for part in path.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.linux_access
>>> dev = mtp.linux_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/linux_access.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def remove(self) -> None:
    """Deletes the current directory or file.

    Exceptions:
        IOError: If something went wrong

    Examples:
        >>> import mtp.linux_access
        >>> dev = mtp.linux_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()
    """
    if _gvfs_found:
        full_name = os.path.join(
            _gvfs_search_path, self._port_device.device_start_part + self.full_filename  
        )
        if not os.path.exists(full_name):
            return
        if self.content_type == WPD_CONTENT_TYPE_FILE:
            os.remove(full_name)
        else:
            shutil.rmtree(full_name)
    else:
        self._port_device.libmntp_device.delete_object(self.entry_id)  

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.linux_access
>>> dev = mtp.linux_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/linux_access.py
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
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.linux_access
        >>> dev = mtp.linux_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()
    """
    if _gvfs_found:
        full_filename = os.path.join(
            _gvfs_search_path,
            self._port_device.device_start_part + self.full_filename,  
            filename,
        )
        try:
            _ = shutil.copyfile(inputfilename, full_filename)
        except OSError:
            # Ok can't copy with shutil on older Gnomes (for example Zorin). si we use gio
            gio_full_filename = "mtp://" + full_filename.split("=", 1)[1]
            try:
                _ = subprocess.check_output(
                    f'gio copy "{inputfilename}" "{gio_full_filename}"',
                    shell=True,
                    stderr=subprocess.STDOUT,
                )
            except subprocess.CalledProcessError as err:
                raise IOError(
                    f"Error copying file '{inputfilename}' to '{gio_full_filename}': {urllib.parse.unquote(err.output.decode('utf-8'))}"  # pyright: ignore[reportAny]
                ) from err
        # shutil.copy(inputfilename, full_filename)
    else:
        _ = self._port_device.libmntp_device.send_file_from_file(  
            inputfilename, filename, self.storage_id, self.entry_id
        )

get_content_from_device_path(dev, fpath)

Get the content of a path.

Parameters:

Name Type Description Default
dev PortableDevice

The instance of PortableDevice where the path is searched

required
fpath 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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> if os.path.exists(_gvfs_search_path):
...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
... else:
...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
>>> cont = mtp.linux_access.get_content_from_device_path(dev[0], n)
>>> str(cont)
'PortableDeviceContent Camera (1)'
>>> dev[0].close()
Source code in mtp/linux_access.py
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
def get_content_from_device_path(dev: PortableDevice, fpath: str) -> PortableDeviceContent | None:
    """Get the content of a path.

    Parameters:
        dev: The instance of PortableDevice where the path is searched
        fpath: 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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> if os.path.exists(_gvfs_search_path):
        ...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        ... else:
        ...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        >>> cont = mtp.linux_access.get_content_from_device_path(dev[0], n)
        >>> str(cont)
        'PortableDeviceContent Camera (1)'
        >>> dev[0].close()
    """
    fpath = fpath.replace("\\", os.path.sep)
    if fpath == dev.devicename:
        raise IOError("get_content_from_device_path needs a devicename and a storage as paramter")
    if _gvfs_found:
        full_fpath = os.path.join(
            _gvfs_search_path, dev.device_start_part + fpath  
        )
        if not os.path.exists(full_fpath):
            return None
        content_type = WPD_CONTENT_TYPE_DIRECTORY if os.path.isdir(full_fpath) else WPD_CONTENT_TYPE_FILE
        return PortableDeviceContent(
            dev,
            fpath,
            1,
            1,
            content_type,
        )
    else:
        parts = fpath.split(os.sep)
        storname_to_search = os.path.join(parts[0], parts[1])
        found_stor = None
        for stor in dev.get_content():
            if stor.full_filename == storname_to_search:
                found_stor = stor
                break
        if found_stor is None:
            raise IOError(f"The storage {storname_to_search} could not be found")
        cont = found_stor
        for pp in parts[2:]:
            cont = cont.get_child(pp)
            if cont is None:
                return None
        return cont

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.linux_access
>>> devs = mtp.linux_access.get_portable_devices()
>>> len(devs) == 1
True
>>> devs[0].close()
Source code in mtp/linux_access.py
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
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.linux_access
        >>> devs = mtp.linux_access.get_portable_devices()
        >>> len(devs) == 1
        True
        >>> devs[0].close()
    """
    global _gvfs_found
    devices: list[PortableDevice] = []
    if not os.path.exists(_gvfs_search_path):
        # We assume, we are not on a GNOME system with installed gvfs
        # So we try to use libmtp
        if _libmtp is None:
            _init_libmtp()
        if _libmtp is None:
            raise OSError("Can't init libmtp")
        for entry in _libmtp.detect_devices():  # type: ignore
            dev = PortableDevice(entry)
            # Device is not ready if we don't get a content
            if len(dev.get_content()) != 0:
                devices.append(dev)
    else:
        _gvfs_found = True
        for entry in os.scandir(_gvfs_search_path):
            dev = PortableDevice(entry.name)
            # Device is not ready if we don't get a content
            if len(dev.get_content()) != 0:
                devices.append(dev)
    return devices

makedirs(dev, create_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
create_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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> if os.path.exists(_gvfs_search_path):
...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
... else:
...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
>>> cont = mtp.linux_access.makedirs(dev[0], n)
>>> str(cont)
'PortableDeviceContent Test (1)'
>>> cont.remove()
>>> dev[0].close()
Source code in mtp/linux_access.py
829
830
831
832
833
834
835
836
837
838
839
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
def makedirs(dev: PortableDevice, create_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
        create_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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> if os.path.exists(_gvfs_search_path):
        ...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
        ... else:
        ...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera/Test"
        >>> cont = mtp.linux_access.makedirs(dev[0], n)
        >>> str(cont)
        'PortableDeviceContent Test (1)'
        >>> cont.remove()
        >>> dev[0].close()
    """
    path: str = create_path.replace("\\", os.path.sep)
    if _gvfs_found:
        try:
            fullpath = os.path.join(
                _gvfs_search_path, dev.device_start_part + path  
            )
            if not os.path.exists(fullpath):
                os.makedirs(fullpath, exist_ok=True)
            cont = get_content_from_device_path(dev, path)
        except (IOError, IndexError) as err:
            raise IOError(f"Error creating directory '{path}': {err.args[1]}") from err
        if cont is None:
            raise IOError(f"Error creating directory '{path}'")
    else:
        found_stor = None
        parts = path.split(os.sep)
        if len(parts) <= 2:
            raise IOError(f"Devicename and or storage are missing in  {path}")
        storname_to_search = os.path.join(parts[0], parts[1])
        for stor in dev.get_content():
            if stor.full_filename == storname_to_search:
                found_stor = stor
                break
        if found_stor is None:
            raise IOError(f"The storage {storname_to_search} could not be found")
        cont = found_stor
        for pp in parts[2:]:
            par_cont = cont
            cont = cont.get_child(pp)
            if cont is None:
                cont = par_cont.create_content(pp)
    return cont

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 and 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
None

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.linux_access
>>> dev = mtp.linux_access.get_portable_devices()
>>> if os.path.exists(_gvfs_search_path):
...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
... else:
...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
>>> for r, d, f in mtp.linux_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/linux_access.py
746
747
748
749
750
751
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
792
793
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
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]], None, None]:
    """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 and 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.linux_access
        >>> dev = mtp.linux_access.get_portable_devices()
        >>> if os.path.exists(_gvfs_search_path):
        ...    n = "Android_Android_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        ... else:
        ...    n = "Nokia 6_Nokia 6_PLEGAR1791402808/Interner gemeinsamer Speicher/DCIM/Camera"
        >>> for r, d, f in mtp.linux_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()
    """
    path = path.replace("\\", os.path.sep)
    if (cont := get_content_from_device_path(dev, path)) is None:
        return
    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():
                contenttype = child.content_type
                if contenttype in [
                    WPD_CONTENT_TYPE_STORAGE,
                    WPD_CONTENT_TYPE_DIRECTORY,
                ]:
                    directories.append(child)
                elif contenttype == WPD_CONTENT_TYPE_FILE:
                    files.append(child)
                if callback and not callback(child.full_filename):
                    directories = []
                    files = []
                    return
            directories.sort(key=lambda ent: ent.full_filename)
            files.sort(key=lambda ent: ent.full_filename)
            yield cont.full_filename, directories, files
        except Exception as err:
            if error_callback is not None:
                if not error_callback(str(err)):
                    directories = []
                    files = []
                    return
            else:
                raise IOError from err
        walk_cont.extend(directories)