الفرق بين المراجعتين ل"Python/pathlib/PurePath"

من موسوعة حسوب
اذهب إلى التنقل اذهب إلى البحث
سطر 1: سطر 1:
== الصنف <code>pathlib.PurePath</code> في بايثون ==
+
== الصنف <code>pathlib.PurePath</code> في بايثون==
 
يمكن للمسارات النقية أن تكون مفيدةٌ في بعض الحالات الخاصة المماثلة لما يلي:
 
يمكن للمسارات النقية أن تكون مفيدةٌ في بعض الحالات الخاصة المماثلة لما يلي:
# لمعالجة مسارات نظام ويندوز أثناء العمل على جهاز يعمل بنظام يونكس (والعكس بالعكس)، حيث لا يمكنك إنشاء كائن من الصنف <code>WindowsPath</code> عند العمل على نظام يونكس، ولكن يمكنك إنشاء كائن من الصنف <code>PureWindowsPath</code>.
+
#لمعالجة مسارات نظام ويندوز أثناء العمل على جهاز يعمل بنظام يونكس (والعكس بالعكس)، حيث لا يمكنك إنشاء كائن من الصنف <code>WindowsPath</code> عند العمل على نظام يونكس، ولكن يمكنك إنشاء كائن من الصنف <code>PureWindowsPath</code>.
# عليك التأكد بأن الشيفرة البرمجية تعالج المسارات فقط دون الوصول الفعلي إلى نظام التشغيل، ففي هذه الحالة، يمكنك إنشاء كائن من أحد الأصناف النقية، فهي لا تملك عمليات تسمح لها بالوصول إلى نظام التشغيل.
+
#عليك التأكد بأن الشيفرة البرمجية تعالج المسارات فقط دون الوصول الفعلي إلى نظام التشغيل، ففي هذه الحالة، يمكنك إنشاء كائن من أحد الأصناف النقية، فهي لا تملك عمليات تسمح لها بالوصول إلى نظام التشغيل.
#  
+
#
 
+
==11.1.2.‏ ‎‏PurePaths‏==
== 11.1.2.‏ ‎‏PurePaths‏ ==
 
 
الكائنات المنشأة من الصنف المسارات النقية تقدم عمليات لمعالجة المسارات بحيث لا يتم الوصول الفعلي إلى نظام الملفات. توجد ثلاث طرائق للوصول إلى هذه الأصناف، ونسمي هذه الطرائق بالنكهات. 
 
الكائنات المنشأة من الصنف المسارات النقية تقدم عمليات لمعالجة المسارات بحيث لا يتم الوصول الفعلي إلى نظام الملفات. توجد ثلاث طرائق للوصول إلى هذه الأصناف، ونسمي هذه الطرائق بالنكهات. 
  
سطر 91: سطر 90:
  
 
<nowiki>******************</nowiki>
 
<nowiki>******************</nowiki>
 
+
===11.1.2.1. General properties===
=== 11.1.2.1. General properties ===
 
 
Paths are immutable and hashable. Paths of a same flavour are comparable and orderable. These properties respect the flavour’s case-folding semantics:
 
Paths are immutable and hashable. Paths of a same flavour are comparable and orderable. These properties respect the flavour’s case-folding semantics:
  
سطر 128: سطر 126:
  
 
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
 
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
 
+
===11.1.2.2. Operators===
=== 11.1.2.2. Operators ===
 
 
The slash operator helps create child paths, similarly to os.path.join():
 
The slash operator helps create child paths, similarly to os.path.join():
  
سطر 189: سطر 186:
  
 
Calling bytes is only recommended under Unix. Under Windows, the unicode form is the canonical representation of filesystem paths.
 
Calling bytes is only recommended under Unix. Under Windows, the unicode form is the canonical representation of filesystem paths.
 
+
===11.1.2.3. Accessing individual parts===
=== 11.1.2.3. Accessing individual parts ===
 
 
To access the individual “parts” (components) of a path, use the following property:
 
To access the individual “parts” (components) of a path, use the following property:
  
سطر 212: سطر 208:
  
 
(note how the drive and local root are regrouped in a single part)
 
(note how the drive and local root are regrouped in a single part)
 
+
===11.1.2.4. Methods and properties===
=== 11.1.2.4. Methods and properties ===
 
 
Pure paths provide the following methods and properties:
 
Pure paths provide the following methods and properties:
  

مراجعة 06:22، 29 يوليو 2018

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

يمكن للمسارات النقية أن تكون مفيدةٌ في بعض الحالات الخاصة المماثلة لما يلي:

  1. لمعالجة مسارات نظام ويندوز أثناء العمل على جهاز يعمل بنظام يونكس (والعكس بالعكس)، حيث لا يمكنك إنشاء كائن من الصنف WindowsPath عند العمل على نظام يونكس، ولكن يمكنك إنشاء كائن من الصنف PureWindowsPath.
  2. عليك التأكد بأن الشيفرة البرمجية تعالج المسارات فقط دون الوصول الفعلي إلى نظام التشغيل، ففي هذه الحالة، يمكنك إنشاء كائن من أحد الأصناف النقية، فهي لا تملك عمليات تسمح لها بالوصول إلى نظام التشغيل.

11.1.2.‏ ‎‏PurePaths‏

الكائنات المنشأة من الصنف المسارات النقية تقدم عمليات لمعالجة المسارات بحيث لا يتم الوصول الفعلي إلى نظام الملفات. توجد ثلاث طرائق للوصول إلى هذه الأصناف، ونسمي هذه الطرائق بالنكهات. 

class pathlib.PurePath(*pathsegments)

هو صنف عام يمثل نكهة مسار النظام (حيث يُنشأ كائن من نوع PurePosixPath أو PureWindowsPath عند إنشاء كائن منه)

>>> PurePath('setup.py')      # يتم العمل على نظام يونكس

PurePosixPath('setup.py')

يمكن لكل عنصر من الوسيط pathsegments أن يكون سلسلة نصية تمثل قطعة مسار أو كائنًا ينفذ الواجهة os.PathLike التي تعيد سلسلة نصية، كما يمكن أن تكون كائن مسار آخر.

>>> PurePath('foo', 'some/path', 'bar')

PurePosixPath('foo/some/path/bar')

>>> PurePath(Path('foo'), Path('bar'))

PurePosixPath('foo/bar')

ويُفترض وجود المسار '.' عندما يكون الوسيط pathsegments  خاليًا:

>>> PurePath()

PurePosixPath('.')

عندما تُعطى عدة مسارات مطلقة، يُعتبر المسار الأخير على أنه مسار المبدأ(anchor) (بشكل مطابق لسلوك التابع os.path.join)

>>> PurePath('/etc', '/usr', 'lib64')

PurePosixPath('/usr/lib64')

>>> PureWindowsPath('c:/Windows', 'd:bar')

PureWindowsPath('d:bar')

عند العمل في مسارات ويندوز، فإن تغيير مجلد الجذر المحلي لا يؤدي إلى إهمال إعدادات القرص السابق

>>> PureWindowsPath('c:/Windows', '/Program Files')

PureWindowsPath('c:/Program Files')

يُضمّ رمز الشرطة '/' المكرر وكذلك النقطة المفردة، إلا أنه لا يُتعامل بالمثل مع النقطتين المزدوجتين '..' وذلك لأن هذا قد يغير دلالة المسار في حال استخدام الروابط الرمزية:

>>> PurePath('foo//bar')

PurePosixPath('foo/bar')

>>> PurePath('foo/./bar')

PurePosixPath('foo/bar')

>>> PurePath('foo/../bar')

PurePosixPath('foo/../bar')

قد يبدو للوهلة الأولى أن المسار ‎‎‎PurePosixPath('foo/../bar')‎‎ يجب أن يكون مساويًا للمسارPurePosixPath('bar')‎ ولكن ذلك غير صحيح إذا كان المجلد 'foo' رابطًا رمزيًّا (symbolic link) لمجلد آخر

تقوم كائنات المسار النقي بتنفيذ الواجهة os.PathLike، بما يسمح باستخدامها في أي مكان تُقبل في هذه الواجهة.

تغيرت في النسخة 3.6: أُضيف الدعم للواجهة os.PathLike

class pathlib.PurePosixPath(*pathsegments)

هو صنف فرعي من الصنف PurePath، ويمثل مسارات أنظمة الملفات المغايرة لنظام ويندوز

>>> PurePosixPath('/etc')

PurePosixPath('/etc')

يتحدد الوسيط pathsegments بشكل مشابه لما هو عليه في PurePath.

class pathlib.PureWindowsPath(*pathsegments)

هو صنف الفرعي من الصنف PurePath، ويمثل مسارات نظام الملفات في ويندوز

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

PureWindowsPath('c:/Program Files')

يتم تحديد الوسيط pathsegments بشكل مشابه لما هو عليه في PurePath.

يمكنك إنشاء كائنات من أيٍّ من الأصناف المذكورة آنفًا على أي نظام تشغيل، وذلك لأنها لا تقوم بأي استدعاءات من النظام.

******************

11.1.2.1. General properties

Paths are immutable and hashable. Paths of a same flavour are comparable and orderable. These properties respect the flavour’s case-folding semantics:

>>>

>>> PurePosixPath('foo') == PurePosixPath('FOO')

False

>>> PureWindowsPath('foo') == PureWindowsPath('FOO')

True

>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }

True

>>> PureWindowsPath('C:') < PureWindowsPath('d:')

True

Paths of a different flavour compare unequal and cannot be ordered:

>>>

>>> PureWindowsPath('foo') == PurePosixPath('foo')

False

>>> PureWindowsPath('foo') < PurePosixPath('foo')

Traceback (most recent call last):

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

TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'

11.1.2.2. Operators

The slash operator helps create child paths, similarly to os.path.join():

>>>

>>> p = PurePath('/etc')

>>> p

PurePosixPath('/etc')

>>> p / 'init.d' / 'apache2'

PurePosixPath('/etc/init.d/apache2')

>>> q = PurePath('bin')

>>> '/usr' / q

PurePosixPath('/usr/bin')

A path object can be used anywhere an object implementing os.PathLike is accepted:

>>>

>>> import os

>>> p = PurePath('/etc')

>>> os.fspath(p)

'/etc'

The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:

>>>

>>> p = PurePath('/etc')

>>> str(p)

'/etc'

>>> p = PureWindowsPath('c:/Program Files')

>>> str(p)

'c:\\Program Files'

Similarly, calling bytes on a path gives the raw filesystem path as a bytes object, as encoded by os.fsencode():

>>>

>>> bytes(p)

b'/etc'

Note

Calling bytes is only recommended under Unix. Under Windows, the unicode form is the canonical representation of filesystem paths.

11.1.2.3. Accessing individual parts

To access the individual “parts” (components) of a path, use the following property:

PurePath.parts

A tuple giving access to the path’s various components:

>>>

>>> p = PurePath('/usr/bin/python3')

>>> p.parts

('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')

>>> p.parts

('c:\\', 'Program Files', 'PSF')

(note how the drive and local root are regrouped in a single part)

11.1.2.4. Methods and properties

Pure paths provide the following methods and properties:

PurePath.drive

A string representing the drive letter or name, if any:

>>>

>>> PureWindowsPath('c:/Program Files/').drive

'c:'

>>> PureWindowsPath('/Program Files/').drive

''

>>> PurePosixPath('/etc').drive

''

UNC shares are also considered drives:

>>>

>>> PureWindowsPath('//host/share/foo.txt').drive

'\\\\host\\share'

PurePath.root

A string representing the (local or global) root, if any:

>>>

>>> PureWindowsPath('c:/Program Files/').root

'\\'

>>> PureWindowsPath('c:Program Files/').root

''

>>> PurePosixPath('/etc').root

'/'

UNC shares always have a root:

>>>

>>> PureWindowsPath('//host/share').root

'\\'

PurePath.anchor

The concatenation of the drive and root:

>>>

>>> PureWindowsPath('c:/Program Files/').anchor

'c:\\'

>>> PureWindowsPath('c:Program Files/').anchor

'c:'

>>> PurePosixPath('/etc').anchor

'/'

>>> PureWindowsPath('//host/share').anchor

'\\\\host\\share\\'

PurePath.parents

An immutable sequence providing access to the logical ancestors of the path:

>>>

>>> p = PureWindowsPath('c:/foo/bar/setup.py')

>>> p.parents[0]

PureWindowsPath('c:/foo/bar')

>>> p.parents[1]

PureWindowsPath('c:/foo')

>>> p.parents[2]

PureWindowsPath('c:/')

PurePath.parent

The logical parent of the path:

>>>

>>> p = PurePosixPath('/a/b/c/d')

>>> p.parent

PurePosixPath('/a/b/c')

You cannot go past an anchor, or empty path:

>>>

>>> p = PurePosixPath('/')

>>> p.parent

PurePosixPath('/')

>>> p = PurePosixPath('.')

>>> p.parent

PurePosixPath('.')

Note

This is a purely lexical operation, hence the following behaviour:

>>>

>>> p = PurePosixPath('foo/..')

>>> p.parent

PurePosixPath('foo')

If you want to walk an arbitrary filesystem path upwards, it is recommended to first call Path.resolve()so as to resolve symlinks and eliminate “..” components.

PurePath.name

A string representing the final path component, excluding the drive and root, if any:

>>>

>>> PurePosixPath('my/library/setup.py').name

'setup.py'

UNC drive names are not considered:

>>>

>>> PureWindowsPath('//some/share/setup.py').name

'setup.py'

>>> PureWindowsPath('//some/share').name

''

PurePath.suffix

The file extension of the final component, if any:

>>>

>>> PurePosixPath('my/library/setup.py').suffix

'.py'

>>> PurePosixPath('my/library.tar.gz').suffix

'.gz'

>>> PurePosixPath('my/library').suffix

''

PurePath.suffixes

A list of the path’s file extensions:

>>>

>>> PurePosixPath('my/library.tar.gar').suffixes

['.tar', '.gar']

>>> PurePosixPath('my/library.tar.gz').suffixes

['.tar', '.gz']

>>> PurePosixPath('my/library').suffixes

[]

PurePath.stem

The final path component, without its suffix:

>>>

>>> PurePosixPath('my/library.tar.gz').stem

'library.tar'

>>> PurePosixPath('my/library.tar').stem

'library'

>>> PurePosixPath('my/library').stem

'library'

PurePath.as_posix()

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

>>>

>>> p = PureWindowsPath('c:\\windows')

>>> str(p)

'c:\\windows'

>>> p.as_posix()

'c:/windows'

PurePath.as_uri()

Represent the path as a file URI. ValueError is raised if the path isn’t absolute.

>>>

>>> p = PurePosixPath('/etc/passwd')

>>> p.as_uri()

'file:///etc/passwd'

>>> p = PureWindowsPath('c:/Windows')

>>> p.as_uri()

'file:///c:/Windows'

PurePath.is_absolute()

Return whether the path is absolute or not. A path is considered absolute if it has both a root and (if the flavour allows) a drive:

>>>

>>> PurePosixPath('/a/b').is_absolute()

True

>>> PurePosixPath('a/b').is_absolute()

False

>>> PureWindowsPath('c:/a/b').is_absolute()

True

>>> PureWindowsPath('/a/b').is_absolute()

False

>>> PureWindowsPath('c:').is_absolute()

False

>>> PureWindowsPath('//some/share').is_absolute()

True

PurePath.is_reserved()

With PureWindowsPath, return True if the path is considered reserved under Windows, False otherwise. With PurePosixPath, False is always returned.

>>>

>>> PureWindowsPath('nul').is_reserved()

True

>>> PurePosixPath('nul').is_reserved()

False

File system calls on reserved paths can fail mysteriously or have unintended effects.

PurePath.joinpath(*other)

Calling this method is equivalent to combining the path with each of the other arguments in turn:

>>>

>>> PurePosixPath('/etc').joinpath('passwd')

PurePosixPath('/etc/passwd')

>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))

PurePosixPath('/etc/passwd')

>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')

PurePosixPath('/etc/init.d/apache2')

>>> PureWindowsPath('c:').joinpath('/Program Files')

PureWindowsPath('c:/Program Files')

PurePath.match(pattern)

Match this path against the provided glob-style pattern. Return True if matching is successful, Falseotherwise.

If pattern is relative, the path can be either relative or absolute, and matching is done from the right:

>>>

>>> PurePath('a/b.py').match('*.py')

True

>>> PurePath('/a/b/c.py').match('b/*.py')

True

>>> PurePath('/a/b/c.py').match('a/*.py')

False

If pattern is absolute, the path must be absolute, and the whole path must match:

>>>

>>> PurePath('/a.py').match('/*.py')

True

>>> PurePath('a/b.py').match('/*.py')

False

As with other methods, case-sensitivity is observed:

>>>

>>> PureWindowsPath('b.py').match('*.PY')

True

PurePath.relative_to(*other)

Compute a version of this path relative to the path represented by other. If it’s impossible, ValueError is raised:

>>>

>>> p = PurePosixPath('/etc/passwd')

>>> p.relative_to('/')

PurePosixPath('etc/passwd')

>>> p.relative_to('/etc')

PurePosixPath('passwd')

>>> p.relative_to('/usr')

Traceback (most recent call last):

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

 File "pathlib.py", line 694, in relative_to

   .format(str(self), str(formatted)))

ValueError: '/etc/passwd' does not start with '/usr'

PurePath.with_name(name)

Return a new path with the name changed. If the original path doesn’t have a name, ValueError is raised:

>>>

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')

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

PureWindowsPath('c:/Downloads/setup.py')

>>> p = PureWindowsPath('c:/')

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

Traceback (most recent call last):

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

 File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name

   raise ValueError("%r has an empty name" % (self,))

ValueError: PureWindowsPath('c:/') has an empty name

PurePath.with_suffix(suffix)

Return a new path with the suffix changed. If the original path doesn’t have a suffix, the new suffix is appended instead:

>>>

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')

>>> p.with_suffix('.bz2')

PureWindowsPath('c:/Downloads/pathlib.tar.bz2')

>>> p = PureWindowsPath('README')

>>> p.with_suffix('.txt')

PureWindowsPath('README.txt')