概要
pythonのディレクトリ、ファイル操作のときに使うモジュールのまとめです。
パスからディレクトリ名を取得する(os.path.dirname)
terminal
>>> os.path.dirname("/aaa/bbb/ccc/ddd.txt")
'/aaa/bbb/ccc'
パスからファイル名を取得する(os.path.basename)
terminal
>>> os.path.basename("/aaa/bbb/ccc/ddd.txt")
'ddd.txt'
パスからディレクトリ名とファイル名を取得する(os.path.split)
terminal
>>> dir, file = os.path.split("/aaa/bbb/ccc/ddd.txt")
>>> dir
'/aaa/bbb/ccc'
>>> file
'ddd.txt'
パス、ファイル名から拡張子を取得する(os.path.splitext)
terminal
>>> dir, ext = os.path.splitext("/aaa/bbb/ccc/ddd.txt")
>>> dir
'/aaa/bbb/ccc/ddd'
>>> ext
'.txt'
パスを結合する(os.path.join)
terminal
>>> dir = "/aaa/bbb/ccc"
>>> file = "ddd.txt"
>>> os.path.join(dir, file)
'/aaa/bbb/ccc/ddd.txt'
ディレクトリを生成する(os.makedirs)
terminal
>>> os.makedirs("./1/2/3", exist_ok=True)
ディレクトリ"1"と"2"がなければ一緒に生成されます。
exist_ok=Trueにしておくと、すでにディレクトリが存在していても例外を発生させずに無視します。
ディレクトリを削除する(shutil.rmtree)
terminal
>>> os.makedirs("./1/2/3", exist_ok=True)
>>> shutil.rmtree("./1")
この場合、ディレクトリ"1","2","3"全てが削除されます。
terminal
>>> os.makedirs("./1/2/3", exist_ok=True)
>>> shutil.rmtree("./1/2/3")
この場合は、ディレクトリ"3"のみが削除されます。
ファイルをコピーする(shutil.copyfile/shutil.copy)
名前を指定してコピーする。
terminal
>>> shutil.copyfile("./test.txt", "./test2.txt")
'./test2.txt'
コピー元のファイル名でコピーする。
terminal
>>> shutil.copy("./test.txt", "./temp")
'./temp/test.txt'
ファイルを移動する(shutil.move)
terminal
>>> shutil.move("./test.txt", "./temp")
'./temp/test.txt'
ディレクトリかどうか判定する(os.path.isdir)
terminal
>>> os.makedirs("./1", exist_ok=True)
>>> os.path.isdir("./1")
True
ファイルかどうか判定する(os.path.isfile)
terminal
>>> os.path.isfile("./test.txt")
True
ディレクトリ,ファイルが存在するかどうか判定する(os.path.exists)
terminal
>>> os.path.exists("./1")
True
>>> os.path.exists("./test.txt")
True
画像の形式を判定する(imghdr.what)
terminal
>>> imghdr.what("./1.png")
'png'
>>> imghdr.what("./2.jpg") # 2.jpgはpng形式の画像ファイル
'png'
>>> imghdr.what("./test.txt") # 画像以外のファイルは何もしない
>>>
imghdrを使うと指定したファイルの画像形式がわかります。
拡張子が間違ったファイルでも正しい画像形式を返します。
例えば、以下の例では"2.jpg"は拡張子はjpegですが、中身はpng形式のファイルです。