Python」カテゴリーアーカイブ

プログラミング言語「Python」に関するカテゴリーです。

Pythonでディレクトリを再帰的にスキャン

Pythonでディレクトリを再帰的にスキャンしてファイルを取得したい場合はos.scandirを使って次のような感じでできるそうです。

>>> import os
>>> def scandir(path='.'):
...   for e in os.scandir(path):
...     if e.is_dir():
...       yield from scandir(e.path)
...     else:
...       yield e
...
>>> for e in scandir():
...   print(e.path)
...
./directory/file1.txt
./directory/file2.txt
./file3.txt

シンボリックリンクかどうかのチェックはfollow_symlinksが使えるようです。

e.is_dir(follow_symlinks = False)

リンク

os — Miscellaneous operating system interfaces — Python 3.7.2 documentation
https://docs.python.org/3/library/os.html

Pythonのリストをインデックス付きでforループ

Pythonのリストをインデックス付きでforループしたい場合はenumerateを使うと良いそうです。

使い方は次のような感じです。

>>> w = ['Sun', 'Mon','Tue','Wed', 'Thu', 'Fri', 'Sat']
>>> for index, value in enumerate(w):
...   print('w[{}] = {}'.format(index, value))
...
w[0] = Sun
w[1] = Mon
w[2] = Tue
w[3] = Wed
w[4] = Thu
w[5] = Fri
w[6] = Sat

PythonのString Formattingを拡張

Python 3で追加されたformatを使うと文字列操作が便利になります。

使い方は次のような感じです。(参考:Pythonの新しい文字列書式操作

>>> '{0} + {1} = {2}'.format(1, 2, 1+2)
'1 + 2 = 3'

string.Formatterを継承すると、この文字列操作を拡張することができるそうです。

拡張の仕方は以下のような感じです。

class Formatter(string.Formatter):
  def format_field(self, value, spec):
    # 必要な処理
    return 'value'

サンプル

このstring.Formatterを継承してupperlowerを書式指定文字列に使うと大文字・小文字に変換するサンプルを作ってみました。

import string
class Formatter(string.Formatter):
  def format_field(self, value, spec):
    if spec == 'upper': value, spec = value.upper(), ''
    elif spec == 'lower': value, spec = value.lower(), ''
    return super(Formatter, self).format_field(value, spec)

使い方は以下のような感じです。

>>> f = Formatter()
>>> f.format('{name} {name:upper} {name:lower}', name='Alice')
'Alice ALICE alice'

template engine

このString Formattingを使ってtemplate engineのようなことを実装したサンプルのようなものも公開されているみたいです。

GitHub – ebrehault/superformatter
https://github.com/ebrehault/superformatter

repeatcallifに対応していて、次のような感じで使えます。

>>> from engine import SuperFormatter
>>> sf = SuperFormatter()
>>> print(sf.format('{n:repeat:n={{item}}\n}', n=[2,3,5,7]))
n=2
n=3
n=5
n=7

現状ではサンプル程度のものかと思いますが、面白そうなテクニックかなと思います。

リンク

string — Common string operations — Python 3.7.2 documentation
https://docs.python.org/3/library/string.html

The world’s simplest Python template engine — Makina Corpus
https://makina-corpus.com/blog/metier/2016/the-worlds-simplest-python-template-engine