LoginSignup
1
6

More than 1 year has passed since last update.

Pythonによるディレクトリ・ファイル操作まとめ

Last updated at Posted at 2021-06-24

ディレクトリ構成を出力

treeコマンドを用いるとディレクトリ構成を以下のように出力できます。
.
├── dir2
│   ├── dir3
│   ├── file1
│   └── file2
├── dir4
├── file1
├── file2
├── file3
└── file4

treeコマンドは以下のようにインストールできます。

brew install tree

試しにpythonで適当なディレクトリやファイルを作成します。os.makedirsの引数にexist_ok=Trueを入れると、既にディレクトリが存在する場合はスキップされてエラーが出ないので便利です。

import os

# ディレクトリを作成
os.makedirs('dir1/dir2/dir3', exist_ok=True)
os.makedirs('dir1/dir4', exist_ok=True)

# 空のファイルを作成
for i in range(1, 5):
    with open(f'dir1/file{i}', 'w') as f:
        f.write('')

for i in range(1, 3):
    with open(f'dir1/dir2/file{i}', 'w') as f:
        f.write('')

treeコマンドを入力すると、作成したディレクトリ構成が出力されます。

cd dir1
tree

.
├── dir2
│   ├── dir3
│   ├── file1
│   └── file2
├── dir4
├── file1
├── file2
├── file3
└── file4

再帰的な検索

glob.glob('**', recursive=True)の構文を用いると、カレントディレクトリ以下すべてのファイルやディレクトリからキーワードに一致するものを取得できます。

import glob

keyword = 'file'
path_list = [path for path in glob.glob('dir1/**', recursive=True) if keyword in path]
print(path_list)

# 出力結果
# ['dir1/file3', 'dir1/file4', 'dir1/file2', 'dir1/dir2/file2', 'dir1/dir2/file1', 'dir1/file1']

ファイルの削除

os.removeを用いることでファイルを削除することができます。

import os
os.remove('dir1/file1')

ファイルやディレクトリのコピー・移動

shutilを用いることでファイルやディレクトリのコピー・移動を行えます。

import shutil

# shutil.move('source', 'destination')
shutil.copy('dir1/file2', 'dir1/dir3')
shutil.move('dir1/file2', 'dir1/dir3')

ディレクトリの削除

shutil.rmtreeを用いることでディレクトリを削除できます。

import shutil

shutil.rmtree('dir1')
1
6
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
1
6