Pathlib

Содержание:

Class hierarchy

The pathlib module implements a simple hierarchy of classes:

                +----------+
                |          |
       ---------| PurePath |--------
       |        |          |       |
       |        +----------+       |
       |             |             |
       |             |             |
       v             |             v
+---------------+    |    +-----------------+
|               |    |    |                 |
| PurePosixPath |    |    | PureWindowsPath |
|               |    |    |                 |
+---------------+    |    +-----------------+
       |             v             |
       |          +------+         |
       |          |      |         |
       |   -------| Path |------   |
       |   |      |      |     |   |
       |   |      +------+     |   |
       |   |                   |   |
       |   |                   |   |
       v   v                   v   v
  +-----------+           +-------------+
  |           |           |             |
  | PosixPath |           | WindowsPath |
  |           |           |             |
  +-----------+           +-------------+

This hierarchy divides path classes along two dimensions:

  • a path class can be either pure or concrete: pure classes support only
    operations that don’t need to do any actual I/O, which are most path
    manipulation operations; concrete classes support all the operations
    of pure classes, plus operations that do I/O.
  • a path class is of a given flavour according to the kind of operating
    system paths it represents. pathlib implements two flavours: Windows
    paths for the filesystem semantics embodied in Windows systems, POSIX
    paths for other systems.

Any pure class can be instantiated on any system: for example, you can
manipulate PurePosixPath objects under Windows, PureWindowsPath
objects under Unix, and so on. However, concrete classes can only be
instantiated on a matching system: indeed, it would be error-prone to start
doing I/O with WindowsPath objects under Unix, or vice-versa.

Furthermore, there are two base classes which also act as system-dependent
factories: PurePath will instantiate either a PurePosixPath or a
PureWindowsPath depending on the operating system. Similarly, Path
will instantiate either a PosixPath or a WindowsPath.

Project details

License: MIT License (GNU General Public License)

Author: Matthijs labots

Requires: Python >=3

Classifiers

  • Development Status

    • 4 — Beta

    • 5 — Production/Stable

  • Framework

    • Django

    • Django :: 2.2

    • IDLE

  • License

    OSI Approved :: MIT License

  • Natural Language

    • Dutch

    • English

  • Operating System

    OS Independent

  • Programming Language

    • Python

    • Python :: 3

    • Python :: 3.0

    • Python :: 3.1

    • Python :: 3.2

    • Python :: 3.3

    • Python :: 3.4

    • Python :: 3.5

    • Python :: 3.6

    • Python :: 3.7

  • Topic

    • Desktop Environment :: File Managers

    • Documentation

    • Internet

    • Internet :: File Transfer Protocol (FTP)

    • Internet :: WWW/HTTP

    • Other/Nonlisted Topic

    • Scientific/Engineering

    • Scientific/Engineering :: Mathematics

    • Scientific/Engineering :: Visualization

    • Security :: Cryptography

    • Software Development

    • Software Development :: Build Tools

    • Software Development :: Code Generators

    • Software Development :: Compilers

    • Software Development :: Libraries

    • Software Development :: Libraries :: Python Modules

    • Software Development :: Testing

    • Software Development :: User Interfaces

    • System

    • System :: Installation/Setup

    • System :: Operating System

    • System :: Software Distribution

    • Text Processing :: Markup :: HTML

Генератор случайных файлов

Создадим папку , а внутри нее еще одну — . Дерево каталогов теперь должно выглядеть вот так:

ManageFiles/
 |
 |_RandomFiles/

Чтобы поиграться с файлами, мы сгенерируем их случайным образом в директории . Создайте файл в папке . Вот что должно получиться:

ManageFiles/
 |
 |_ create_random_files.py
 |_RandomFiles/

Готово? Теперь поместите в файл следующий код, и перейдем к его рассмотрению:

import os
from pathlib import Path
import random

list_of_extensions = 

# перейти в папку RandomFiles
os.chdir('./RandomFiles')

for item in list_of_extensions:
    # создать 20 случайных файлов для каждого расширения имени
    for num in range(20):
        # пусть имя файла начинается со случайного числа от 1 до 50
        file_name = random.randint(1, 50)
        file_to_create = str(file_name) + item
        Path(file_to_create).touch()

Начиная с Python 3.4 мы получили pathlib, нашу маленькую волшебную палочку. Также мы импортируем функцию для генерации случайных чисел, но ее мы посмотрим в действии чуть ниже.

Сперва создадим
список файловых расширений для формирования названий файлов. Не стесняйтесь
добавить туда свои варианты.

Далее мы переходим в папку и запускаем цикл. В нем мы просто говорим: возьми каждый элемент и сделай с ним кое-что во внутреннем цикле 20 раз.

Теперь пришло время для импортированной функции . Используем ее для производства случайных чисел от 1 до 50. Это просто не очень творческий способ побыстрее дать названия нашим тестовым файлам: к сгенерированному числу добавим расширение файла и получим что-то вроде или . И так 20 раз для каждого расширения. В итоге образуется беспорядок, достаточный для того, чтобы его было лень сортировать вручную.

Итак, запустим
наш генератор хаоса через терминал.

python create_random_files.py

Поздравляю,
теперь у нас полная папка неразберихи. Будем распутывать.

В той же директории, где , создадим файл и поместим туда следующий код.

DirEntry fields being «static» attribute-only objects

In this July 2014 python-dev message,
Paul Moore suggested a solution that was a «thin wrapper round the OS
feature», where the DirEntry object had only static attributes:
name, path, and is_X, with the st_X attributes only
present on Windows. The idea was to use this simpler, lower-level
function as a building block for higher-level functions.

At first there was general agreement that simplifying in this way was
a good thing. However, there were two problems with this approach.
First, the assumption is the is_dir and similar attributes are
always present on POSIX, which isn’t the case (if d_type is not
present or is DT_UNKNOWN). Second, it’s a much harder-to-use API
in practice, as even the is_dir attributes aren’t always present
on POSIX, and would need to be tested with hasattr() and then
os.stat() called if they weren’t present.

sys.exit

Данная функция позволяет разработчику выйти из Python. Функция exit принимает необязательный аргумент, обычно целое число, которое дает статус выхода. Ноль считается как успешное завершение. Обязательно проверьте, имеет ли ваша операционная система какие-либо особые значения для своих статусов выхода, чтобы вы могли следить за ними в своем собственном приложении

Обратите внимание на то, что когда вы вызываете exit, это вызовет исключение SystemExit, которое позволяет функциям очистки работать в конечных пунктах блоков try / except. Давайте взглянем на то, как вызывается данная функция:

Python

import sys
sys.exit(0)

Traceback (most recent call last):
File «<pyshell#5>», line 1, in <module>
sys.exit(0)
SystemExit: 0

1
2
3
4
5
6
7

importsys

sys.exit()

Traceback(most recent call last)

File»<pyshell#5>»,line1,in<module>

sys.exit()

SystemExit

Запустив данный код в IDLE, вы увидите возникшую ошибку SystemExit. Давайте создадим несколько скриптов для теста. Для начала вам нужно создать основной скрипт, программу, которая будет вызывать другой скрипт Python. Давайте назовем его “call_exit.py”. Скрипт должен содержать следующее:

call_exit.py

Python

import subprocess

code = subprocess.call()
print(code)

1
2
3
4

importsubprocess

code=subprocess.call(«python.exe»,»exit.py»)

print(code)

Теперь создайте скрипт Python под названием“exit.py” и сохраните его в той же папке. Вставьте в него следующий код:

exit.py

Python

import sys

sys.exit(0)

1
2
3

importsys

sys.exit()

Теперь давайте запустим его:

sys.exit

Как вы могли заметить, написанный нами скрипт exit вернул ноль, так что он успешно заработал. Получается, мы заодно научились вызывать разные скрипты Python изнутри самого Python!

Notes on exception handling

DirEntry.is_X() and DirEntry.stat() are explicitly methods
rather than attributes or properties, to make it clear that they may
not be cheap operations (although they often are), and they may do a
system call. As a result, these methods may raise OSError.

For example, DirEntry.stat() will always make a system call on
POSIX-based systems, and the DirEntry.is_X() methods will make a
stat() system call on such systems if readdir() does not
support d_type or returns a d_type with a value of
DT_UNKNOWN, which can occur under certain conditions or on
certain file systems.

Often this does not matter — for example, os.walk() as defined in
the standard library only catches errors around the listdir()
calls.

Also, because the exception-raising behaviour of the DirEntry.is_X
methods matches that of pathlib — which only raises OSError
in the case of permissions or other fatal errors, but returns False
if the path doesn’t exist or is a broken symlink — it’s often
not necessary to catch errors around the is_X() calls.

However, when a user requires fine-grained error handling, it may be
desirable to catch OSError around all method calls and handle as
appropriate.

For example, below is a version of the get_tree_size() example
shown above, but with fine-grained error handling added:

Return values being (name, stat_result) two-tuples

Initially this PEP’s author proposed this concept as a function called
iterdir_stat() which yielded two-tuples of (name, stat_result).
This does have the advantage that there are no new types introduced.
However, the stat_result is only partially filled on POSIX-based
systems (most fields set to None and other quirks), so they’re not
really stat_result objects at all, and this would have to be
thoroughly documented as different from os.stat().

Also, Python has good support for proper objects with attributes and
methods, which makes for a saner and simpler API than two-tuples. It
also makes the DirEntry objects more extensible and future-proof
as operating systems add functionality and we want to include this in
DirEntry.

See also some previous discussion:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *