LoginSignup
3
1

More than 5 years have passed since last update.

pathlibを使って特定ディレクトリ以下の全ファイルを取得する

Last updated at Posted at 2018-09-01

はじめに

テキストファイルを分かち書きするのにファイルを全て結合させて処理していたが、サイズが大きすぎてメモリが悲鳴を上げたのでファイルを1つずつ開いて処理することにした。
そのため、まずは全ファイルを取得して1つずつ開くコードを書いた。

コード

Path().rglob('*') を使う
対象のファイルの拡張子が決まっているならPath().rglob("*.txt") のように書けばよいのだが、私が扱いたいファイルは拡張子がないのでis_file() を使ってファイルのみを返すようなメソッドを書く。

from pathlib import Path


def main():
    for path in get_file('./text'):
        with path.open("r", encoding='utf-8') as file:
            file.read()

def get_file(dirctory):
    for f in Path(dirctory).rglob('*'):
        if f.is_file():
            yield f

コード(修正前)

良くない書き方

from pathlib import Path


def main():
    for path in get_file('./text'):
        with path.open("r", encoding='utf-8') as file:
            file.read()

def get_file(dirctory):
    d = Path(dirctory).iterdir()
    for f in d:
        if f.is_file():
            yield f
        elif f.is_dir():
            yield from get_file(f)

if __name__ == '__main__':
    main()
3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1