Python shutilモジュールの使い方
1162 ワード
1.shutil.copyfile(oldfile, newfile)
ファイル1をtxtファイルなどのファイル2にコピーします.注意:ファイル2が存在しない場合は、ファイル2が直接作成され、ファイル2の内容とファイル1の内容は同じです.ファイル2が存在すると、ファイル2の既存の内容が消去される.
構文:shutil.copyfile(oldfile, newfile)
2.shutil.copy(olddir, newdir)
olddirのファイルをnewdirにコピーするには、遍歴します.
3.shutil.move(olddir, newdir)
olddirのファイルを1つずつnewdirに移動したり、フォルダ全体や中のファイルを一度に別のフォルダに移動したりすることができます.
構文:shutil.move(olddir, newdir)
ファイル1をtxtファイルなどのファイル2にコピーします.注意:ファイル2が存在しない場合は、ファイル2が直接作成され、ファイル2の内容とファイル1の内容は同じです.ファイル2が存在すると、ファイル2の既存の内容が消去される.
構文:shutil.copyfile(oldfile, newfile)
import shutil
oldfile = "1.txt"
newfile = "2.txt"
shutil.copyfile(oldfile, newfile)
2.shutil.copy(olddir, newdir)
olddirのファイルをnewdirにコピーするには、遍歴します.
import shutil
for i in range(2):
oldfile = "./dir_1/%d.txt"%(i+1)
newfile = "./dir_2"
shutil.copy(oldfile, newfile)
3.shutil.move(olddir, newdir)
olddirのファイルを1つずつnewdirに移動したり、フォルダ全体や中のファイルを一度に別のフォルダに移動したりすることができます.
構文:shutil.move(olddir, newdir)
code1:
import shutil
for i in range(2):
oldfile = "./dir_1/%d.txt"%(i+1)
newfile = "./dir_2/%d.txt"%(i+1)
shutil.move(oldfile, newfile)
import shutil
for i in range(2):
oldfile = "./dir_1/%d.txt"%(i+1)
newfile = "./dir_2"
shutil.move(oldfile, newfile)
code2:
import shutil
oldfile = "./dir_1"
newfile = "./dir_2"
shutil.move(oldfile, newfile)