ファイルを移動する方法【Python】

何でもできそうなosモジュールですが、ファイルの移動はできません。
ファイルを移動するときはshutilモジュールの出番となります。
shutilモジュールはファイルに対するコピーや削除の関数を提供しています。

import os
import shutil
base_path = os.path.dirname(os.path.abspath(__file__))
# 移動するファイルを作成します。
file_path = os.path.join(base_path, "movetest.txt")
f = open(file_path, 'w', encoding='UTF-8')
f.write("移動テスト")
f.close()
# 移動先のフォルダを作成します。
dest_path = os.path.join(base_path, "dest")
if os.path.isdir(dest_path) == False:
  os.makedirs(dest_path)
# ファイルを移動します。
shutil.move(file_path, dest_path)

実行結果

なし
[dest]フォルダ内に[movetest.txt]が作成されます。

Python

Posted by @erestage