LoginSignup
2
4

More than 5 years have passed since last update.

Python > library > os > os.walk() > ディレクトリ構造を取得 / 指定ディレクトリ内の各ファイルパスを取得する実装

Last updated at Posted at 2017-03-27
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Python 3.6.0 on virtualenv

https://docs.python.org/3/library/os.html
をふと眺めていて気になった関数os.walk()

os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up.

試してみた (on Python 3.6.0)。

準備

$ mkdir -p TOP/MIDDLE/BOTTOM
$ touch TOP/MIDDLE/mfile1.txt
$ touch TOP/MIDDLE/mfile2.txt
$ touch TOP/MIDDLE/BOTTOM/bfile1.txt
$ touch TOP/MIDDLE/BOTTOM/bfile2.txt
$ touch TOP/tfile1.txt

code > os.walk()の結果を表示

test_python_170327a.py
import os

res = os.walk(".")
for elem in res:
    print(elem)

結果
$ python test_python_170327a.py 
('.', ['TOP'], ['test_python_170325b.py', 'test_python_170327a.py'])
('./TOP', ['MIDDLE'], ['tfile1.txt'])
('./TOP/MIDDLE', ['BOTTOM'], ['mfile2.txt', 'mfile1.txt'])
('./TOP/MIDDLE/BOTTOM', [], ['bfile2.txt', 'bfile1.txt'])

code > 各ファイルのパスを取得

https://docs.python.org/3/library/os.html
のサンプルコードを参考に以下のように実装した。

test_python_170327b.py
import os

res = os.walk(".")
for elem in res:
    dirpath, dirnames, filenames = elem
    for afile in filenames:
        res = os.path.join(dirpath, afile)
        print(res)
結果
$ python test_python_170327b.py 
./test_python_170327b.py
./test_python_170325b.py
./test_python_170327a.py
./TOP/tfile1.txt
./TOP/MIDDLE/mfile2.txt
./TOP/MIDDLE/mfile1.txt
./TOP/MIDDLE/BOTTOM/bfile2.txt
./TOP/MIDDLE/BOTTOM/bfile1.txt

code > refactoring後

(追記 2017/03/28)

test_python_170328a.py
import os

for dirpath, dirnames, filenames in os.walk("."):
    for afile in filenames:
        res = os.path.join(dirpath, afile)
        print(res)

余分な処理を整理してすっきりしました。

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