LoginSignup
13
30

More than 5 years have passed since last update.

ファイル操作でよく使うモジュール[os,shutil,glob]

Last updated at Posted at 2017-11-19

こちらもご参考に
Pathlibチートシート

モジュールのインポート

import.py
import os
import shutil
import glob

パス関連

現在のパスを取得
os.getcwd()
カレントディレクトリの変更
os.chdir(path)
ディレクトリの作成
os.mkdir(path)
パスにある要素のリスト取得
os.listdir(path)
絶対パスを返す。(ただし、os.path.join(path,filename) に同じ)
os.path.abspath(filename)
パスの末尾の名前を取得
os.path.basename(path)
パスの親フォルダ名を取得
os.path.dirname(path)
パスが存在すればTrue
os.path.exists(path)
パスの結合
os.path.join(path,filename)
パスを末尾とそれ以外に分離
os.path.split(path)

globを使った検索

指定した拡張子(例えばjpg)のリストを取得
glob.glob(path+'/*.jpg')
再帰的にファイルを検索する
glob.glob(path+'/*.jpg, recursive=True)
正規表現でも検索できる
glob.glob(path+'/*[0-9].jpg)

ファイル操作

ファイルのコピー
shutil.copy(from_path, to_path)
ディレクトリ全体のコピー
shutil.copytree(from_path, to_path)
ファイルの削除
os.remove(path)
ディレクトリ全体の削除
shutil.rmtree(path)
ファイル名の変更
os.rename(before_path, after_path)

13
30
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
13
30