4
7

More than 3 years have passed since last update.

[python glob] 私の好きな複数のファイル読み込みの方法

Last updated at Posted at 2021-03-22

python globとは

pythonにはさまざまなモジュールがあり,その中で私はglobというのが結構好きで使っていました.
簡単に説明すると,
glob=掴む
的な意味なので,複数のファイルを探るといったときに使えます.

使い方

まず,複数のファイルを用意します.
a000.txt
a001.txt
a002.txt
a003.txt
a004.txt
があったとします.

a.py
import glob
a = glob.glob('./a*.txt')
print(a)
> python .\a.py

['.\a000.txt', '.\a001.txt', '.\a002.txt', '.\a003.txt', '.\a004.txt']

こんな感じで結果が表示されます.
このようにa***.txtのファイルを探すことに成功しました.もしディレクトリ内にb***.txtといったファイルがある場合,それは読み込みされずa始まりのファイルのみが選択されます.

そして使った後に数値ファイルであれあnumpy.loadtxt,ファイル形式であればfileを使ったおなじみの手法でファイル内のデータを読み込めます.

例えば,file形式でファイル読み込みの場合,

b.py
import glob
a = glob.glob('./a*.txt')
print(a)
for i in a:
    print(i)
    with open(i) as f:
        b = f.read()
        print(b)

['.\a000.txt', '.\a001.txt', '.\a002.txt', '.\a003.txt', '.\a004.txt']
.\a000.txt
this is 1
.\a001.txt
this is 2
.\a002.txt
this is 3
.\a003.txt
this is 4
.\a004.txt
this is 5

こんな感じで表示されます.

4
7
1

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
4
7