作った目的
Pythonでディレクトリ一覧を取得するために調べていたら、pathlibライブラリのことを知りました。
動作確認のために簡単なテストプログラムを作りました。
環境
- Windows10
- Python 3.7.7
- Ubuntuでも動作しました。
一覧の取得
ただ一覧を取得するだけなら下記のコードで可能です。
import pathlib
dir = r"c:\users\username" # Windows
# dir = "/home/username" # Ubuntu
pathlib_obj = pathlib.Path(dir)
files = list(pathlib_obj.glob("*"))
for i in files:
print(i)
テスト プログラムについて
起動すると、ディレクトリの前に数字が表示されます。
その数字を入力してEnterを押すと、指定のディレクトリの一覧が表示されます。
終了は、qを入力してEnterです。
pathlist_test.py
import pathlib
def filelist_print(pathlib_obj):
# カレントディレクトリの表示
print(f"===== カレントディレクトリ:{pathlib_obj} =====")
# ファイル一覧の取得
files = list(pathlib_obj.glob("*"))
# ディレクトリとそれ以外を分ける
dir_list = [pathlib.Path("..")]
file_list = []
for file in files:
if file.is_dir() is True:
dir_list.append(file)
else:
file_list.append(file)
# ディレクトリの一覧を表示
dir_no = 0
for file in dir_list:
print(f"{str(dir_no).rjust(3, ' ')} Dir : {file.name}")
dir_no += 1
# ディレクトリ以外の一覧を表示
for file in file_list:
print(f" File : {file.name}")
# ディレクトリの一覧を返す
return dir_list
def chk_int(input_str):
if str.isdigit(input_str) is True:
# 入力文字をintに変換して返す
return int(input_str)
# intに変換できない場合は、-1を返す
return -1
# メイン
if __name__ == "__main__":
# カレントディレクトリの取得
pathlib_obj = pathlib.Path().resolve()
# 以下、ループです
while True:
# ディレクトリにある一覧の表示
dir_list = filelist_print(pathlib_obj)
# ディレクトリの番号の入力待ち
input_str = input("input Dir number (q: Quit): ")
# 入力文字が「q」なら終了
if input_str == "q":
break
# 入力文字をintに変換
input_int = chk_int(input_str)
if input_int == -1:
# 入力文字がintに変換できない場合は、なにもしない
continue
elif input_int == 0:
# 入力値が0の場合は、親ディレクトリへ移動
pathlib_obj = pathlib_obj.parent
else:
if len(dir_list) > input_int:
# 入力値がディレクトリ番号の場合は、そのディレクトリへ移動
pathlib_obj = pathlib.Path(dir_list[input_int]).resolve()
最後に
作り込みはしていませんし、一覧取得の目的は達成したので、ここまでしか作っていません。
VSCodeでマウス操作しないで、複数のディレクトリ構造の確認するときに意外と使えました。