shutilモジュールによる高水準ファイル操作
出典:
#■■■■■ shutilによるファイルコピー
#出典
#■shutilによる「ファイルコピー」(元も残る)
# path of source file & destination
import shutil
path_file_source = "***"
path_file_destination = "XXX"
shutil.copyfile(path_file_source, path_file_destination)
# shutil.copy(path_old, path_new) #コピー動作は同様。パーミッションもコピー
# shutil.copy2(path_old, path_new) #パーミッション、メタデータともコピー
# ディレクトリツリーまるごとコピーならshutil.copytree(path_old, path_new)。# pathはファイルでなくディレクトリでなければならない。
#元を削除するなら以下!
import os
os.remove(path_old)
#■shutilによる「ファイル移動」
ファイルパスからファイルパスを指定する。
元のファイルは、コピー後に削除される。
import shutil
path_old = './test_old/old.txt'
path_new = './test_old/new.txt'
shutil.move(path_old, path_new)
#■ファイル名変更
・いちばん簡単な方法: os.rename() 関数。
import os
os.rename('filename.txt', 'new_filename.txt')
・ファイルが作業ディレクトリになければそのフルパス指定
import os
os.rename('/path/to/dir/filename.txt', '/path/to/dir/new_filename.txt')
・shutilによる方法
import shutil
shutil.move('/path/to/dir/filename.txt', '/path/to/dir/new_filename.txt')