Python/pathlib/Path

من موسوعة حسوب
< Python‏ | pathlib
مراجعة 21:50، 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

يعيد معلومات عن المسار (مماثل للتابع os.stat) ، ويتم حساب المعلومات في كل مرة يتم فيها استدعاء التابع

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

>>> p.stat().st_size

956

>>> p.stat().st_mtime

1327883547.852554

التابع Path.chmod

يقوم هذا التابع بتغيير نمط الملف وصلاحياته (مماثل للتابع os.chmod)

>>>

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

>>> p.stat().st_mode

33277

>>> p.chmod(0o444)

>>> p.stat().st_mode

33060

التابع Path.exists

يدلّ على كون المسار مشيرًا إلى ملف أو مجلد حقيقي أم لا

>>>

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

True

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

True

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

True

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

False

ملاحظة: إذا كان المسار يشير إلى اختصار (symlink) فإن استدعاء التابع exists يدل على ما يشير إليه الاختصار.

التابع Path.expanduser

يعيد كائن مسار جديد يمدد فيه المسار الرئيسي للمستخدم الممثل بالرمز '~'، مشابه للتابع os.path.expanduser

>>>

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

>>> p.expanduser()

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

New in version 3.5.

التابع Path.glob

تعيد جميع الملفات التي تحقق نمط glob المعطى، مهما كان نوع الملف

>>>

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

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

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

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

يعني النمط "**" تحديد المجلد الحالي وجميه المجلدات الفرعية في داخله بشكل عودي (recursively)، وهو ما يسمّى 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')]

ملاحظة: احذر من استخدام النمط "**" في أشجار المجلدات الكبيرة، فإن ذلك قد يستهلك كمية هائلة من الوقت,

التابع Path.group

يعيد هذا التابع اسم المجموعة التي ينتمي لها الملف، ويرمي بالخطأ KeyError إذا كان معرف المجموعة gid الخاص بالملف غير موجود في قاعدة بيانات النظام.

التابع Path.is_dir

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى مجلد (أو إلى اختصار يشير إلى مجلد)، بينما يعيد False في حال كان المسار يشير إلى أي نوع آخر من الملفات.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع Path.is_file

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى ملف نظامي(أو إلى اختصار يشير إلى ملف نظامي)، بينما يعيد False في حال كان المسار يشير إلى أي نوع آخر من الملفات.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع Path.is_mount

يعيد هذا التابع القيمة المنطقية True إذا كان المسار هو نقطة تثبيت (mount point) .

التابع Path.is_symlink

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى رابط دلالي (symbolic link)، وFalse فيما عدا ذلك.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع Path.is_socket

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى Unix socket (أو إلى اختصار يشير إلىUnix socket)، بينما يعيد False في حال كان المسار يشير إلى أي نوع آخر من الملفات.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع Path.is_fifo

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى FIFO (أو إلى اختصار يشير إلى FIFO)، بينما يعيد False في حال كان المسار يشير إلى أي نوع آخر من الملفات.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع Path.is_block_device

يعيد هذا التابع القيمة المنطقية True إذا كان المسار يشير إلى block device (أو إلى اختصار يشير إلى block device)، بينما يعيد False في حال كان المسار يشير إلى أي نوع آخر من الملفات.

كما أنه عيد False إذا كان المسار غير موجود أو أن الاختصار بشير إلى مسار غير موجود، كما يمكن لأخطاء أخرى (مثل عدم وجود صلاحيات) أن تظهر.

التابع 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.