Python 如何利用os跟shutil來控制檔案複製修改跟刪除!
最近因為在研究如何用python整理資料
那就會遇到需要操作資料夾或是檔案的問題,所以就研究了一下怎麼用Python操作
操作也很簡單最常使用的模組就是os跟shutil這兩個
這邊就寫一下幾個常用的操作
使用os模組
import os
新增資料夾(單層目錄)
os.mkdir('./test/')
新增資料夾(多層目錄, 如前一層test資料夾不存在, 將自動新增)
os.makedirs('./test/save/', exist_ok=True)
判斷資料夾(目錄)是否存在
if not os.path.isdir('./test/'):
print('資料夾不存在')
刪除單個文件
os.remove('file.jpg')
合併目錄位址
os.path.join('./test/', 'test.jpg')
輸出為’./test/test.jpg’
os.path.join('./test/', 'save/', 'test.jpg')
輸出為’./test/save/test.jpg’
搜尋多層目錄內的檔案
for root, dirs, files in os.walk('./test/'):
for i in files:
fullpath = os.path.join(root, i)
輸出為’./test/t/test01.jpg’ ‘./test/k/test02.jpg’ …….
使用shutil模組
import shutil
複製資料夾所有檔案至新建資料夾內
shutil.copytree('A', 'B')
A跟B都只能是目錄位置, 且B必須不存在
shutil.copytree會自動生成B目錄, 如果B本來就存在會出現Error
參考寫法: shutil.copytree(‘C:/test/’, ‘D:/newTest/’)
刪除目錄以及目錄內的所有檔案
shutil.rmtree('./test/')
複製文件
shutil.copyfile('A', 'B')
A跟B只能是檔案, 不能是目錄位址
參考寫法: shutil.copyfile(‘test.jpg’, ‘newTest.jpg’)
複製目錄或者複製目錄內的檔案
shutil.copy('A', 'B')
移動文件
shutil.move('A', 'B')