Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

こちらもご参考に
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)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした