Перебор большого массива с одинаковыми по размеру, но меньшими массивами

Сейчас 2018, и Python уже давно эволюционировали __future__. Итак, как насчет использования удивительного pathlib , следующего с Python 3.4, для выполнения задачи вместо того, чтобы бороться с os, os.path, glob, shutil и т. Д.

Итак, у нас есть 3 пути (возможно, дублируется):

  • mod_path: это путь к простейшему вспомогательному скрипту
  • src_path: содержит пару файлов шаблонов , ожидающих копирования.
  • cwd: текущий каталог , назначение этого шаблона файлов.

, и проблема в том, что у нас нет полного пути к src_path, только знаете, что это относительный путь к mod_path.

Теперь давайте решим это с удивительным pathlib :

# Hope you don't be imprisoned by legacy Python code :)
from pathlib import Path

# `cwd`: current directory is straightforward
cwd = Path.cwd()

# `mod_path`: According to the accepted answer and combine with future power
# if we are in the `helper_script.py`
mod_path = Path(__file__).parent
# OR if we are `import helper_script`
mod_path = Path(helper_script.__file__).parent

# `src_path`: with the future power, it's just so straightforward
relative_path_1 = 'same/parent/with/helper/script/'
relative_path_2 = '../../or/any/level/up/'
src_path_1 = (mod_path / relative_path_1).resolve()
src_path_2 = (mod_path / relative_path_2).resolve()

В будущем это просто так просто. : D


Кроме того, мы можем выбирать и проверять и копировать / перемещать эти файлы шаблонов с помощью pathlib :

if src_path != cwd:
    # When we have different types of files in the `src_path`
    for template_path in src_path.glob('*.ini'):
        fname = template_path.name
        target = cwd / fname
        if not target.exists():
            # This is the COPY action
            with target.open(mode='wb') as fd:
                fd.write(template_path.read_bytes())
            # If we want MOVE action, we could use:
            # template_path.replace(target)

1
задан 18 January 2019 в 14:52
поделиться