批量複製或者刪除檔案,(複製+刪除)就等於移動,呵呵
其中複製檔案有兩種方法:#coding=utf-8
import os
import shutil
#遞迴複製資料夾內的檔案
defcopyfiles
(sourcedir,targetdir):
#忽略某些特定的子資料夾
if sourcedir.find("exceptionfolder")>0:
return
#列出源目錄檔案和資料夾
for file in os.listdir(sourcedir):
#拼接完整路徑
sourcefile = os.path.join(sourcedir,file)
targetfile = os.path.join(targetdir,file)
#如果是檔案則處理
if os.path.isfile(sourcefile):
#如果目的路徑不存在該檔案就建立空檔案,並保持目錄層級結構
ifnot os.path.exists(targetdir):
os.makedirs(targetdir)
#如果目的路徑裡面不存在某個檔案或者存在那個同名檔案但是檔案有殘缺,則複製,否則跳過
ifnot os.path.exists(targetfile) or (os.path.exists(targetfile) and (os.path.getsize(targetfile) != os.path.getsize(sourcefile))):
open(targetfile, "wb").write(open(sourcefile, "rb").read())
print targetfile+" copy succeeded"
#如果是資料夾則遞迴
if os.path.isdir(sourcefile):
copyfiles(sourcefile, targetfile)
#遍歷某個目錄及其子目錄下所有檔案拷貝到某個目錄中
defcopyfiles2
(srcpath,dstpath):
ifnot os.path.exists(srcpath):
"src path not exist!"
ifnot os.path.exists(dstpath):
os.makedirs(dstpath)
#遞迴遍歷資料夾下的檔案,用os.walk函式返回乙個三元組
for root,dirs,files in os.walk(srcpath):
for eachfile in files:
shutil.copy(os.path.join(root,eachfile),dstpath)
print eachfile+" copy succeeded"
#刪除某目錄下特定檔案
defremovefileindir
(sourcedir):
for file in os.listdir(sourcedir):
file=os.path.join(sourcedir,file) #必須拼接完整檔名
檔案讀寫操作,如果是文字可以用r和b,或者**等用rb,wb二進位制模式讀寫
用第三方模組shutil,一般python都預裝了
python指令碼程式設計 批量修改指定目錄內檔名
對單個目錄下檔案字尾名 demo.py coding utf 8 import os 列出當前目錄下所有的檔案 files os.listdir for filename in files portion os.path.splitext filename 如果字尾是.mp4 if portion ...
python 批量改名指令碼
第66屆艾美獎上,絕命毒師 一舉拿下了劇情類最佳劇集 最佳男主 最佳男女配角和最佳劇本5項重要大獎,成為艾美獎最大的贏家。這部歷時六年,共62集的劇集憑藉metacritic metacritic的評分是收錄各 的評分,並綜合得出的評分 99分 滿分100 的成績,成為寫入健力士世界紀錄大全的 世界...
用python實現批量複製
使用shutil實現簡單的檔案批量複製 src dir為複製檔案的原始檔,就是從 複製,target dir 是目標檔案,就是要複製到哪 shutil.copy src dir,target dir 完整 import os import shutil 呼叫複製檔案函式 defcopy2file s...