LoginSignup
0
3

More than 3 years have passed since last update.

ディレクトリの中身を表示(Python)

Last updated at Posted at 2021-03-19

pythonでディレクトリの中身を表示させる方法を紹介します
(環境はLinux)
また、ファイル構成はこのようにします

/test
test1 #ディレクトリ
test2.txt #ファイル
test3.txt #ファイル
/test/test1
test4.mp3 #ファイル
test5.mp3 #ファイル

ディレクトリの中身を表示させるには

ソースコード
import os
print(os.listdir("/test"))
実行結果
['test1','test2.txt','test3.txt']

pythonでディレクトリの中身を取得するにはos.listdir()を使います
os.listdir()では、中身をリスト化してくれるので、for文を使うと表示させるのが楽です

ソースコード
import os
a = os.listdir("/test")
for p in a:
 print(p)
実行結果
test1
test2
test3

さらにディレクトリかファイルかを分かるように

ソースコード
import os
a = os.listdir("/test")
for p in a:
 if os.path.isdir("/test" + "/" + p) == True:
  d = "ディレクトリ"
 else:
  d = "ファイル"
 print(p + " " + d)
実行結果
test1 ディレクトリ
test2 ファイル
test3 ファイル 

応用

pygameを以下のコマンドでインストール

$ pip install pygame
ソースコード
import os
import pygame
import os
import subprocess
txt = ""
def fileread(file):
 while os.path.isdir(file) == True:
  a = os.listdir(file)
  b = 1
  for p in a:
   if os.path.isdir(file + "/" + p) == True:
    d = "ディレクトリ"
   else:
    d = "ファイル"
   txt = txt + str(b) + " " + p + " " + d + "\n"
   b += 1
  subprocess.call(['cls'])
  print(txt)
  num = input()
  if str(num).isnumeric() == True:
   c = num - 1
   file = file + "/" + a[c]
   continue
  elif num == 0:
   f = file.rfind("/")
   file = file[:f]
   continue
 return file
file = "/test"
filepass = fileread(file)
try:
 pygame.mixer.init()
 pygame.mixer.music.load(filepass)
 pygame.mixer.music.play(1)
except:
 pass
実行結果
1 test1 ディレクトリ
2 test2 ファイル
3 test3 ファイル
       #ここでキーボード入力待ち

subprocess.call(['cls'])を入れてターミナル画面をクリアするかは好みによりますが、自分は嫌いなのでクリアしときます。

ここでは以下の機能を追加しました

  • 中身表示後、ファイル名の横の数字を選択することで、そのファイル(ディレクトリ)に対して操作ができるようにした(この場合はディレクトリを選んだ場合、その中身を表示し、再びキーボード入力待ち。音声ファイルを選んだ場合、それを再生。それ以外の場合は終了)

  • 0と入力することで階層を1つ上がる

なので、このキーボード入力待ちの部分に1と入力すると、

/test/test1
1 test4.mp3 ファイル
2 test5.mp3 ファイル
       #ここでキーボード入力待ち

と表示されます
ここで更に1又は2と入力すると音声ファイルが再生されます

終わり

実用化させるにはもう少し機能を加える必要がありますが、ただ表示させる分には十分だと思います

0
3
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
0
3