使用shutil、os模組協助複製、移動、刪除、新增目錄或檔案
shutil模組
- 安裝模組:
1
pip install pytest-shutil
複製資料夾所有檔案至新建資料夾內
1
2
3shutil.copytree('A','B')
# A和B都可能是目錄位置,但B必須為不存在
# shutil.copytree會自動產生B目錄,如果B目錄存在會出現錯誤訊息。- 參考寫法
1
2import shutil
shutil.copytree('./test1/','D:/test2/')
- 參考寫法
刪除目錄及目錄內所有檔案
1
2import shutil
shutil.rmtree('./test/')複製文件
1
2
3import shutil
shutil.copyfile('A','B')
# A和B只能是檔案,不能是目錄位址- 參考寫法
1
shutil.copyfile('test1.jpg','test2.jpg')
- 參考寫法
複製目錄或者複製目錄內的檔案
1
2
3import shutil
shutil.copy('A','B')
# A只能是目錄,B可以是目錄或檔案移動文件
1
2
3import shutil
shutil.move('A','B')
# A可以是目錄或檔案,B只能是目錄
os模組
不必安裝,內建模組
刪除單個文件
1
2import os
os.remove('test.jpg')判斷資料夾(目錄)是否存在
1
2
3import os
if not os.path.isdir('./test/'):
print('資料夾不存在')新增資料夾(單層目錄)
1
2import os
os.mkdir('./test/')新增資料夾(多層目錄)
如果前一層test資料夾不存在,將會自動新建
1
2
3import os
os.makedirs('./test/hello/',exist_ok=True)
# os.makedirs的exist_ok預設為False,如果資料夾存在的話,將會發生錯誤訊息,因此要記得修改為True,無論目錄是否存在,都會自動判斷新增。合併目錄位址
1
2import os
os.path.join('./test/','hello,jpg')- 輸出為
./test/hello,jpg
 
1
2import os
os.path.join('./testA/','./testB/,'hello.jpg')- 輸出為
./testA/testB/hello.jpg
- 輸出為