الفرق بين المراجعتين لصفحة: «Python/pathlib/Path»

من موسوعة حسوب
سطر 1: سطر 1:
== الصنف <code>pathlib.Path</code> في بايثون==
== الصنف <code>pathlib.Path</code> في بايثون==
هو الصنف العام للأصناف التي تتعامل مع المسارات مع السماح بالقيام بعمليات الإدخال والإخراج، نورد فيما يلي طريقة الاستخدام الأساسية:
هو الصنف العام للأصناف التي تتعامل مع المسارات مع السماح بالقيام بعمليات الإدخال والإخراج، وتُسمّى بأصناف المسارات الصلبة Concrete Paths، نورد فيما يلي طريقة الاستخدام الأساسية:


استيراد الصنف الأساسي من الوحدة <code>pathlib</code>:<syntaxhighlight lang="python3">
استيراد الصنف الأساسي من الوحدة <code>pathlib</code>:<syntaxhighlight lang="python3">
سطر 50: سطر 50:


</syntaxhighlight><span> </span>
</syntaxhighlight><span> </span>
== 11.1.3. Concrete paths ==
Concrete paths are subclasses of the pure path classes. In addition to operations provided by the latter, they also provide methods to do system calls on path objects. There are three ways to instantiate concrete paths:


class pathlib.Path(*pathsegments)
=== نكهات المسارات الصلبة ===
 
يمكن إنشاء كائن من الصنف <code>Path</code> بثلاث طرق مختلفة:
A subclass of PurePath, this class represents concrete paths of the system’s path flavour (instantiating it creates either a PosixPath or a WindowsPath):
 
>>>


1- باستخدام باني الصنف العام Path، وتعتمد هذه الطريقة على إنشاء كائن من الصنف <code>PosixPath</code> أو <code>WindowsPath</code> حسب نظام التشغيل الذي يتم تفسير الشيفرة عليه:<syntaxhighlight lang="python3">
>>> Path('setup.py')
>>> Path('setup.py')


PosixPath('setup.py')
PosixPath('setup.py')


pathsegments is specified similarly to PurePath.
class pathlib.PosixPath(*pathsegments)
A subclass of Path and PurePosixPath, this class represents concrete non-Windows filesystem paths:
>>>


</syntaxhighlight>2- باستخدام باني الصنف الخاص بالأنظمة المغايرة لويندوز <code>PosixPath</code><syntaxhighlight lang="python3">
>>> PosixPath('/etc')
>>> PosixPath('/etc')


PosixPath('/etc')
PosixPath('/etc')


pathsegments is specified similarly to PurePath.
class pathlib.WindowsPath(*pathsegments)
A subclass of Path and PureWindowsPath, this class represents concrete Windows filesystem paths:
>>>


</syntaxhighlight>3- باستخدام باني الصنف الخاص بنظام ويندوز <code>WindowsPath</code><syntaxhighlight lang="python3">
>>> WindowsPath('c:/Program Files/')
>>> WindowsPath('c:/Program Files/')


WindowsPath('c:/Program Files')
WindowsPath('c:/Program Files')


pathsegments is specified similarly to PurePath.
You can only instantiate the class flavour that corresponds to your system (allowing system calls on non-compatible path flavours could lead to bugs or failures in your application):


</syntaxhighlight>إلا أنه يجب الانتباه إلى عدم القيام بأي استدعاءات للنظام عندما ننشئ كائنًا من أحد الصنفين الفرعيين السابقين على نظام تشغيل مغاير له، كما يوضح المثال التالي<syntaxhighlight lang="python3">
>>>
>>>


سطر 97: سطر 79:
>>> os.name
>>> os.name


'posix'
'posix'     #نظام التشغيل الذي يتم تفسير الشيفرة عليه مغاير لويندوز


>>> Path('setup.py')
>>> Path('setup.py')
سطر 107: سطر 89:
PosixPath('setup.py')
PosixPath('setup.py')


>>> WindowsPath('setup.py')
>>> WindowsPath('setup.py') #لا تسمح أصناف المسارات الصلبة بإنشاء كائن مغاير لنوع النظام الذي يتم العمل عليه


Traceback (most recent call last):
Traceback (most recent call last):
سطر 119: سطر 101:
NotImplementedError: cannot instantiate 'WindowsPath' on your system
NotImplementedError: cannot instantiate 'WindowsPath' on your system


=== توابع الصنف <code>Path</code> ===
 
</syntaxhighlight>
===توابع الصنف <code>Path</code>===
يتيح الصنف <code>Path</code> استخدام جميع التوابع الخاصة بالصنف <code>PurePath</code> وذلك لأنه يرث منه، ويضيف عليها التوابع التالية، التي تسمح بالقيام باستدعاءات النظام (system calls)، وترمي هذه التوابع استثناء <code>OSError</code> في حال فشل أيٍّ منها (كأن يكون المسار الذي يتم التعامل معه غير موجود مثلًا).
يتيح الصنف <code>Path</code> استخدام جميع التوابع الخاصة بالصنف <code>PurePath</code> وذلك لأنه يرث منه، ويضيف عليها التوابع التالية، التي تسمح بالقيام باستدعاءات النظام (system calls)، وترمي هذه التوابع استثناء <code>OSError</code> في حال فشل أيٍّ منها (كأن يكون المسار الذي يتم التعامل معه غير موجود مثلًا).


Concrete paths provide the following methods in addition to pure paths methods. Many of these methods can raise an OSError if a system call fails (for example because the path doesn’t exist):
==== التابع <code>Path.cwd</code> ====
 
يعيد كائن مسار جديدًا يمثّل المسار الحالي (بشكل مشابه للتابع os.getcwd)<syntaxhighlight lang="python3">
classmethod Path.cwd()
 
Return a new path object representing the current directory (as returned by os.getcwd()):
 
>>>
 
>>> Path.cwd()
>>> Path.cwd()


PosixPath('/home/antoine/pathlib')
PosixPath('/home/antoine/pathlib')


classmethod Path.home()


Return a new path object representing the user’s home directory (as returned by os.path.expanduser()with ~ construct):
</syntaxhighlight>


>>>
==== التابع <code>Path.home</code> ====
يعيد كائن مسار جديدًا يمثّل المسار الرئيسي (home directory) للمستخدم (بشكل مشابه للتابع os.path.expanduser مع الوسيط <code>'~'</code>)


وهو تابع جديد في النسخة 3.5<syntaxhighlight lang="python3">
>>> Path.home()
>>> Path.home()


PosixPath('/home/antoine')
PosixPath('/home/mostafa')


New in version 3.5.


Path.stat()
</syntaxhighlight>


==== التابع <code>Path.stat</code> ====
Return information about this path (similarly to os.stat()). The result is looked up at each call to this method.
Return information about this path (similarly to os.stat()). The result is looked up at each call to this method.


سطر 162: سطر 141:
1327883547.852554
1327883547.852554


Path.chmod(mode)
==== التابع <code>Path.chmod</code> ====
 
Change the file mode and permissions, like os.chmod():
Change the file mode and permissions, like os.chmod():


سطر 180: سطر 158:
33060
33060


Path.exists()
==== التابع <code>Path.exists</code> ====
 
Whether the path points to an existing file or directory:
Whether the path points to an existing file or directory:


سطر 206: سطر 183:
If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.
If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.


Path.expanduser()
==== التابع <code>Path.expanduser</code> ====
 
Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser():
Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser():


سطر 220: سطر 196:
New in version 3.5.
New in version 3.5.


Path.glob(pattern)
==== التابع <code>Path.glob</code> ====
 
Glob the given pattern in the directory represented by this path, yielding all matching files (of any kind):
Glob the given pattern in the directory represented by this path, yielding all matching files (of any kind):


سطر 254: سطر 229:
Using the “**” pattern in large directory trees may consume an inordinate amount of time.
Using the “**” pattern in large directory trees may consume an inordinate amount of time.


Path.group()
==== التابع <code>Path.group</code> ====
 
Return the name of the group owning the file. KeyError is raised if the file’s gid isn’t found in the system database.
Return the name of the group owning the file. KeyError is raised if the file’s gid isn’t found in the system database.


Path.is_dir()
==== التابع <code>Path.is_dir</code> ====
 
Return True if the path points to a directory (or a symbolic link pointing to a directory), False if it points to another kind of file.
Return True if the path points to a directory (or a symbolic link pointing to a directory), False if it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.is_file()
==== التابع <code>Path.is_file</code> ====
 
Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file.
Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.is_mount()
التابع <code>Path.is_mount</code>


Return True if the path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. Not implemented on Windows.
Return True if the path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. Not implemented on Windows.
سطر 276: سطر 248:
New in version 3.7.
New in version 3.7.


Path.is_symlink()
==== التابع <code>Path.is_symlink</code> ====
 
Return True if the path points to a symbolic link, False otherwise.
Return True if the path points to a symbolic link, False otherwise.


False is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.


Path.is_socket()
==== التابع <code>Path.is_socket</code> ====
 
Return True if the path points to a Unix socket (or a symbolic link pointing to a Unix socket), False if it points to another kind of file.
Return True if the path points to a Unix socket (or a symbolic link pointing to a Unix socket), False if it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.is_fifo()
==== التابع <code>Path.is_fifo</code> ====
 
Return True if the path points to a FIFO (or a symbolic link pointing to a FIFO), False if it points to another kind of file.
Return True if the path points to a FIFO (or a symbolic link pointing to a FIFO), False if it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.is_block_device()
==== التابع <code>Path.is_block_device</code> ====
 
Return True if the path points to a block device (or a symbolic link pointing to a block device), False if it points to another kind of file.
Return True if the path points to a block device (or a symbolic link pointing to a block device), False if it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.is_char_device()
==== التابع <code>Path.is_char_device</code> ====
 
Return True if the path points to a character device (or a symbolic link pointing to a character device), Falseif it points to another kind of file.
Return True if the path points to a character device (or a symbolic link pointing to a character device), Falseif it points to another kind of file.


False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.
False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.


Path.iterdir()
==== التابع <code>Path.iterdir</code> ====
 
When the path points to a directory, yield path objects of the directory contents:
When the path points to a directory, yield path objects of the directory contents:


سطر 332: سطر 298:
PosixPath('docs/Makefile')
PosixPath('docs/Makefile')


Path.lchmod(mode)
==== التابع <code>Path.lchmod</code> ====
 
Like Path.chmod() but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.
Like Path.chmod() but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.


Path.lstat()
===== التابع <code>Path.lstat</code> =====
 
Like Path.stat() but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.
Like Path.stat() but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.


Path.mkdir(mode=0o777, parents=False, exist_ok=False)
==== التابع <code>Path.mkdir</code> ====
 
Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.
Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.


سطر 354: سطر 317:
Changed in version 3.5: The exist_ok parameter was added.
Changed in version 3.5: The exist_ok parameter was added.


Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
==== التابع <code>Path.open</code> ====
 
Open the file pointed to by the path, like the built-in open() function does:
Open the file pointed to by the path, like the built-in open() function does:


سطر 370: سطر 332:
'#!/usr/bin/env python3\n'
'#!/usr/bin/env python3\n'


Path.owner()
==== التابع <code>Path.owner</code> ====
 
Return the name of the user owning the file. KeyError is raised if the file’s uid isn’t found in the system database.
Return the name of the user owning the file. KeyError is raised if the file’s uid isn’t found in the system database.


Path.read_bytes()
==== التابع <code>Path.read_bytes</code> ====
 
Return the binary contents of the pointed-to file as a bytes object:
Return the binary contents of the pointed-to file as a bytes object:


سطر 392: سطر 352:
New in version 3.5.
New in version 3.5.


Path.read_text(encoding=None, errors=None)
==== التابع <code>Path.read_text</code> ====
 
Return the decoded contents of the pointed-to file as a string:
Return the decoded contents of the pointed-to file as a string:


سطر 412: سطر 371:
New in version 3.5.
New in version 3.5.


Path.rename(target)
==== التابع <code>Path.rename</code> ====
 
Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object:
Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object:


سطر 432: سطر 390:
'some text'
'some text'


Path.replace(target)
==== التابع <code>Path.replace</code> ====
 
Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced.
Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced.


Path.resolve(strict=False)
==== التابع <code>Path.resolve</code> ====
 
Make the path absolute, resolving any symlinks. A new path object is returned:
Make the path absolute, resolving any symlinks. A new path object is returned:


سطر 466: سطر 422:
New in version 3.6: The strict argument.
New in version 3.6: The strict argument.


Path.rglob(pattern)
==== التابع <code>Path.rglob</code> ====
 
This is like calling Path.glob() with “**” added in front of the given pattern:
This is like calling Path.glob() with “**” added in front of the given pattern:


سطر 488: سطر 443:
Remove this directory. The directory must be empty.
Remove this directory. The directory must be empty.


Path.samefile(other_path)
==== التابع <code>Path.samefile</code> ====
 
Return whether this path points to the same file as other_path, which can be either a Path object, or a string. The semantics are similar to os.path.samefile() and os.path.samestat().
Return whether this path points to the same file as other_path, which can be either a Path object, or a string. The semantics are similar to os.path.samefile() and os.path.samestat().


سطر 510: سطر 464:
New in version 3.5.
New in version 3.5.


Path.symlink_to(target, target_is_directory=False)
==== التابع <code>Path.symlink_to</code> ====
 
Make this path a symbolic link to target. Under Windows, target_is_directory must be true (default False) if the link’s target is a directory. Under POSIX, target_is_directory’s value is ignored.
Make this path a symbolic link to target. Under Windows, target_is_directory must be true (default False) if the link’s target is a directory. Under POSIX, target_is_directory’s value is ignored.


سطر 536: سطر 489:
The order of arguments (link, target) is the reverse of os.symlink()’s.
The order of arguments (link, target) is the reverse of os.symlink()’s.


Path.touch(mode=0o666, exist_ok=True)
==== التابع <code>Path.touch</code> ====
 
Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.
Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.


Path.unlink()
==== التابع <code>Path.unlink</code> ====
 
Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead.
Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead.


Path.write_bytes(data)
==== التابع <code>Path.write_bytes</code> ====
 
Open the file pointed to in bytes mode, write data to it, and close the file:
Open the file pointed to in bytes mode, write data to it, and close the file:


سطر 564: سطر 514:
New in version 3.5.
New in version 3.5.


Path.write_text(data, encoding=None, errors=None)
==== التابع <code>Path.write_text</code> ====
 
Open the file pointed to in text mode, write data to it, and close the file:
Open the file pointed to in text mode, write data to it, and close the file:


سطر 579: سطر 528:


'Text file contents'
'Text file contents'
<span> </span>


New in version 3.5.
New in version 3.5.

مراجعة 11:04، 29 يوليو 2018

 الصنف pathlib.Path في بايثون

هو الصنف العام للأصناف التي تتعامل مع المسارات مع السماح بالقيام بعمليات الإدخال والإخراج، وتُسمّى بأصناف المسارات الصلبة Concrete Paths، نورد فيما يلي طريقة الاستخدام الأساسية:

استيراد الصنف الأساسي من الوحدة pathlib:

>>> from pathlib import Path #استيراد الصنف الأساسي

إنشاء كائن والتكرار على المجلدات والملفات التي بداخله:

>>> p = Path('.') #إنشاء كائن باستخدام باين الصنف العام

>>> [x for x in p.iterdir() if x.is_dir()] #تعداد المجلدات الموجودة ضمن المسار الحالي 
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
PosixPath('__pycache__'), PosixPath('build')]

تعداد ملفات بايثون المصدرية في شجر ة المجلدات هذه:

>>> list(p.glob('**/*.py'))

[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
PosixPath('build/lib/pathlib.py')]

التنقّل ضمن شجرة المجلدات، يظهر فيه استخدام عملية القسمة / المُعاد تعريفها لتقوم بالتنقل بين المجلدات:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q

PosixPath('/etc/init.d/reboot')
>>> q.resolve()

PosixPath('/etc/rc.d/init.d/halt')

الاستعلام عن خصائص المسار:

>>> q.exists()

True

>>> q.is_dir()

False

فتح ملف:

>>> with q.open() as f: f.readline()

السطر الأول وأهلا بك
السطر الأخير وداعا

نكهات المسارات الصلبة

يمكن إنشاء كائن من الصنف Path بثلاث طرق مختلفة:

1- باستخدام باني الصنف العام Path، وتعتمد هذه الطريقة على إنشاء كائن من الصنف PosixPath أو WindowsPath حسب نظام التشغيل الذي يتم تفسير الشيفرة عليه:

>>> Path('setup.py')

PosixPath('setup.py')

2- باستخدام باني الصنف الخاص بالأنظمة المغايرة لويندوز PosixPath

>>> PosixPath('/etc')

PosixPath('/etc')

3- باستخدام باني الصنف الخاص بنظام ويندوز WindowsPath

>>> WindowsPath('c:/Program Files/')

WindowsPath('c:/Program Files')

إلا أنه يجب الانتباه إلى عدم القيام بأي استدعاءات للنظام عندما ننشئ كائنًا من أحد الصنفين الفرعيين السابقين على نظام تشغيل مغاير له، كما يوضح المثال التالي

>>>

>>> import os

>>> os.name

'posix'     #نظام التشغيل الذي يتم تفسير الشيفرة عليه مغاير لويندوز

>>> Path('setup.py')

PosixPath('setup.py')

>>> PosixPath('setup.py')

PosixPath('setup.py')

>>> WindowsPath('setup.py')  #لا تسمح أصناف المسارات الصلبة بإنشاء كائن مغاير لنوع النظام الذي يتم العمل عليه

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

 File "pathlib.py", line 798, in __new__

   % (cls.__name__,))

NotImplementedError: cannot instantiate 'WindowsPath' on your system

توابع الصنف Path

يتيح الصنف Path استخدام جميع التوابع الخاصة بالصنف PurePath وذلك لأنه يرث منه، ويضيف عليها التوابع التالية، التي تسمح بالقيام باستدعاءات النظام (system calls)، وترمي هذه التوابع استثناء OSError في حال فشل أيٍّ منها (كأن يكون المسار الذي يتم التعامل معه غير موجود مثلًا).

التابع Path.cwd

يعيد كائن مسار جديدًا يمثّل المسار الحالي (بشكل مشابه للتابع os.getcwd)

>>> Path.cwd()

PosixPath('/home/antoine/pathlib')

التابع Path.home

يعيد كائن مسار جديدًا يمثّل المسار الرئيسي (home directory) للمستخدم (بشكل مشابه للتابع os.path.expanduser مع الوسيط '~')

وهو تابع جديد في النسخة 3.5

>>> Path.home()

PosixPath('/home/mostafa')

التابع Path.stat

Return information about this path (similarly to os.stat()). The result is looked up at each call to this method.

>>>

>>> p = Path('setup.py')

>>> p.stat().st_size

956

>>> p.stat().st_mtime

1327883547.852554

التابع Path.chmod

Change the file mode and permissions, like os.chmod():

>>>

>>> p = Path('setup.py')

>>> p.stat().st_mode

33277

>>> p.chmod(0o444)

>>> p.stat().st_mode

33060

التابع Path.exists

Whether the path points to an existing file or directory:

>>>

>>> Path('.').exists()

True

>>> Path('setup.py').exists()

True

>>> Path('/etc').exists()

True

>>> Path('nonexistentfile').exists()

False

Note

If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.

التابع Path.expanduser

Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser():

>>>

>>> p = PosixPath('~/films/Monty Python')

>>> p.expanduser()

PosixPath('/home/eric/films/Monty Python')

New in version 3.5.

التابع Path.glob

Glob the given pattern in the directory represented by this path, yielding all matching files (of any kind):

>>>

>>> sorted(Path('.').glob('*.py'))

[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]

>>> sorted(Path('.').glob('*/*.py'))

[PosixPath('docs/conf.py')]

The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing:

>>>

>>> sorted(Path('.').glob('**/*.py'))

[PosixPath('build/lib/pathlib.py'),

PosixPath('docs/conf.py'),

PosixPath('pathlib.py'),

PosixPath('setup.py'),

PosixPath('test_pathlib.py')]

Note

Using the “**” pattern in large directory trees may consume an inordinate amount of time.

التابع Path.group

Return the name of the group owning the file. KeyError is raised if the file’s gid isn’t found in the system database.

التابع Path.is_dir

Return True if the path points to a directory (or a symbolic link pointing to a directory), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.is_file

Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.is_mount

Return True if the path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. Not implemented on Windows.

New in version 3.7.

التابع Path.is_symlink

Return True if the path points to a symbolic link, False otherwise.

False is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.

التابع Path.is_socket

Return True if the path points to a Unix socket (or a symbolic link pointing to a Unix socket), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.is_fifo

Return True if the path points to a FIFO (or a symbolic link pointing to a FIFO), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.is_block_device

Return True if the path points to a block device (or a symbolic link pointing to a block device), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.is_char_device

Return True if the path points to a character device (or a symbolic link pointing to a character device), Falseif it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

التابع Path.iterdir

When the path points to a directory, yield path objects of the directory contents:

>>>

>>> p = Path('docs')

>>> for child in p.iterdir(): child

...

PosixPath('docs/conf.py')

PosixPath('docs/_templates')

PosixPath('docs/make.bat')

PosixPath('docs/index.rst')

PosixPath('docs/_build')

PosixPath('docs/_static')

PosixPath('docs/Makefile')

التابع Path.lchmod

Like Path.chmod() but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.

التابع Path.lstat

Like Path.stat() but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.

التابع Path.mkdir

Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError.

If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -pcommand), but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

التابع Path.open

Open the file pointed to by the path, like the built-in open() function does:

>>>

>>> p = Path('setup.py')

>>> with p.open() as f:

...    .readline()

...

'#!/usr/bin/env python3\n'

التابع Path.owner

Return the name of the user owning the file. KeyError is raised if the file’s uid isn’t found in the system database.

التابع Path.read_bytes

Return the binary contents of the pointed-to file as a bytes object:

>>>

>>> p = Path('my_binary_file')

>>> p.write_bytes(b'Binary file contents')

20

>>> p.read_bytes()

b'Binary file contents'

New in version 3.5.

التابع Path.read_text

Return the decoded contents of the pointed-to file as a string:

>>>

>>> p = Path('my_text_file')

>>> p.write_text('Text file contents')

18

>>> p.read_text()

'Text file contents'

The optional parameters have the same meaning as in open().

New in version 3.5.

التابع Path.rename

Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object:

>>>

>>> p = Path('foo')

>>> p.open('w').write('some text')

9

>>> target = Path('bar')

>>> p.rename(target)

>>> target.open().read()

'some text'

التابع Path.replace

Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced.

التابع Path.resolve

Make the path absolute, resolving any symlinks. A new path object is returned:

>>>

>>> p = Path()

>>> p

PosixPath('.')

>>> p.resolve()

PosixPath('/home/antoine/pathlib')

“..” components are also eliminated (this is the only method to do so):

>>>

>>> p = Path('docs/../setup.py')

>>> p.resolve()

PosixPath('/home/antoine/pathlib/setup.py')

If the path doesn’t exist and strict is True, FileNotFoundError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists. If an infinite loop is encountered along the resolution path, RuntimeError is raised.

New in version 3.6: The strict argument.

التابع Path.rglob

This is like calling Path.glob() with “**” added in front of the given pattern:

>>>

>>> sorted(Path().rglob("*.py"))

[PosixPath('build/lib/pathlib.py'),

PosixPath('docs/conf.py'),

PosixPath('pathlib.py'),

PosixPath('setup.py'),

PosixPath('test_pathlib.py')]

Path.rmdir()

Remove this directory. The directory must be empty.

التابع Path.samefile

Return whether this path points to the same file as other_path, which can be either a Path object, or a string. The semantics are similar to os.path.samefile() and os.path.samestat().

An OSError can be raised if either file cannot be accessed for some reason.

>>>

>>> p = Path('spam')

>>> q = Path('eggs')

>>> p.samefile(q)

False

>>> p.samefile('spam')

True

New in version 3.5.

التابع Path.symlink_to

Make this path a symbolic link to target. Under Windows, target_is_directory must be true (default False) if the link’s target is a directory. Under POSIX, target_is_directory’s value is ignored.

>>>

>>> p = Path('mylink')

>>> p.symlink_to('setup.py')

>>> p.resolve()

PosixPath('/home/antoine/pathlib/setup.py')

>>> p.stat().st_size

956

>>> p.lstat().st_size

8

Note

The order of arguments (link, target) is the reverse of os.symlink()’s.

التابع Path.touch

Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.

التابع Path.unlink

Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead.

التابع Path.write_bytes

Open the file pointed to in bytes mode, write data to it, and close the file:

>>>

>>> p = Path('my_binary_file')

>>> p.write_bytes(b'Binary file contents')

20

>>> p.read_bytes()

b'Binary file contents'

An existing file of the same name is overwritten.

New in version 3.5.

التابع Path.write_text

Open the file pointed to in text mode, write data to it, and close the file:

>>>

>>> p = Path('my_text_file')

>>> p.write_text('Text file contents')

18

>>> p.read_text()

'Text file contents'

New in version 3.5.