close

使用shutil模組

import shutil

複製資料夾所有檔案至新建資料夾內

shutil.copytree('A', 'B')

#A跟B都只能是目錄位置, 且B必須不存在

# shutil.copytree會自動生成B目錄, 如果B本來就存在會出現Error

參考寫法: shutil.copytree('./original/', 'D:/newDir/') 

 

※刪除目錄以及目錄內的所有檔案※

shutil.rmtree('./test/')

 

※複製文件※

shutil.copyfile('A', 'B')

#A跟B只能是檔案, 不能是目錄位址

參考寫法: shutil.copyfile('oldimg.jpg', 'newimg.jpg')

 

※複製目錄或者複製目錄內的檔案※

shutil.copy('A', 'B')

#A只能是目錄, B可以是目錄或檔案

 

※移動文件※

shutil.move('A', 'B')

 

使用os模組

import os

刪除單個文件

os.remove('oldfile.jpg')

 

判斷資料夾(目錄)是否存在

if not os.path.isdir('./data/'):

    print('資料夾不存在')

 

新增資料夾(單層目錄)

os.mkdir('./data/')

#A跟B都只能是目錄位置, 且B必須不存在

 

新增資料夾(多層目錄, 如前一層data資料夾不存在, 將自動新增)

os.makedirs('./data/save/', exist_ok=True)

#用來新增多層的目錄, 假設前一層data不存在, 系統將自動依序新增data, 並在data內在新增save

#os.makedirs的exist_ok預設為False, 如果資料夾存在的話, 將會發生Error, 因此要記得修改為True, 無論目錄是否存在, 都會自動判斷新增與否 

 

合併目錄位址

os.path.join('./data/', 'test.jpg')

#輸出為'./data/test.jpg'

os.path.join('./data/', 'save/', 'test.jpg')

#輸出為'./data/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' ...

arrow
arrow

    楓綺 發表在 痞客邦 留言(0) 人氣()