LoginSignup
53
50

More than 5 years have passed since last update.

[Python]ディレクトリ内にある複数のファイルをソートして読み込む

Last updated at Posted at 2017-06-02

背景

Python初心者です。
Pythonでディレクトリ内にある複数のテキストファイルを読み込むときに普段は以下のように書いていました。

#coding:utf-8
import glob

if __name__ == '__main__':

  file_list = glob.glob('path/to/dir/*.txt')

  for filename in file_list:
    with open(filename, 'r') as input:
    ...

しかし、このままだと ls -U を叩いたときと同じ順番(ソート無しの状態)でファイルが読み込まれてしまいます。

今回はファイル名でソートされた状態で順番に読み込みたかったので解決法を調べました。

解決策

file_listの部分を以下のように書くことで解決できました。

#coding:utf-8
import glob


if __name__ == '__main__':

  file_list = sorted(glob.glob('path/to/dir/*.txt'))

  for filename in file_list:
    with open(filename, 'r') as input:
    ...

おまけ

他にも import os してからsorted関数のkeyを os.path.getmtime だとか os.path.getsize にすると変更時刻順とかファイルサイズ順にソートして読み込ませることができるみたいです。
便利ですね。

参考文献

How is Pythons glob.glob ordered?

53
50
0

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
53
50