LoginSignup
138
144

More than 5 years have passed since last update.

pythonでフォルダ内のファイル一覧をパス無しで取得する

Posted at

pythonでフォルダの中を見る時ファイル名、ディレクトリ名は欲しいけどパスは要らないって場合には何が一番よいやり方なのでしょうね...

例えばtestディレクトリに以下の様なファイルが存在するとして

test.csv
test.py
test.sh
test.txt
test1
test2
test3

globモジュールを使ったとするとこうなりますよね。


>>> import glob
>>> glob.glob('test/*')
['test/test.csv', 'test/test.py', 'test/test.sh', 'test/test.txt', 'test/test1', 'test/test2', 'test/test3']


ただ、理想としては


>>> import hoge
>>> hoge.hoge('test/*')
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']


このようになって欲しいのです。

 
以下の様な方法もありますが、ワイルドカード指定が出来ないのは辛い。


>>> import os
>>> os.listdir('test/')
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']

 
 
 
以上を踏まえて私が思いついたのは以下の3つ
その中でもよく使うのがcommandsを使う方法です。

>>> import commands
>>> commands.getoutput('ls test/* | xargs -n 1 basename').split("\n")
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']

 
他にはやはりglobモジュールで得たpathのbasenameだけ得るのが正攻法でしょうか。


>>> import glob
>>> [r.split('/')[-1] for r in glob.glob('test/*')]
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']

>>> import glob, os
>>> [os.path.basename(r) for r in glob.glob('test/*')]
['test.csv', 'test.py', 'test.sh', 'test.txt', 'test1', 'test2', 'test3']

 
 

皆様はどのようにしているのか気になったのでとりあえず自分の方法を書いてみました。
なにかいい方法があればご教授下さい。

138
144
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
138
144