python之文件操作-復制、剪切、刪除等


以下是把sourceDir目錄下的以.JPG結尾的文件所有拷貝到targetDir目錄下:

<span style="font-size:18px;">>>>import os
>>> import os.path
>>> import shutil 
>>> def copyFiles(sourceDir,targetDir):
	for files in os.listdir(sourceDir):
		sourceFile = os.path.join(sourceDir,files)   //把文件夾名和文件名稱鏈接起來
		targetFile = os.path.join(targetDir,files)
		if os.path.isfile(sourceFile) and sourceFile.find('.JPG')>0: //要求是文件且后綴是jpg

shutil模塊

復制文件夾

復制文件

復制文件的時候。假設指定的文件目的位置之間有文件夾不存在。則會拋出錯誤。

所以最好在拷貝之間確認文件夾存在。

當文件夾存在的時候,復制文件就沒有問題了。

刪除文件夾使用例如以下函數:

shutil.rmtree('d:/dd')

移動文件或者目錄到另外一個地方:

shutil.move('d:/c.png','e:/')

-------------------------------------------

那么存在一個問題就是。copy函數和copyfile函數二者的差別是什么呢?

看help:

從help中能夠看出來,copyfile不過把文件復制到目的文件。可是copy函數能夠把文件的mode也一起拷貝。比方說原來的文件有+x可運行權限,那么目的文件也會有可運行權限。


刪除一級文件夾下的全部文件:

<span style="font-size:18px;">def removeFileInFirstDir(targetDir): 
     for file in os.listdir(targetDir): 
         targetFile = os.path.join(targetDir,  file) 
         if os.path.isfile(targetFile): //僅僅刪除文件不刪除目錄
             os.remove(targetFile)</span>

文本內容的復制,把文件夾下的全部文件的內容都寫入到目標文件里:

<span style="font-size:18px;">def coverFiles(sourceDir,  targetDir): 
        for file in os.listdir(sourceDir): 
             sourceFile = os.path.join(sourceDir,  file) 
             targetFile = os.path.join(targetDir,  file) 
             #cover the files //復寫?
             if os.path.isfile(sourceFile): 
                 open(targetFile, "wb").write(open(sourceFile, "rb").read())</span>

<span style="font-size:18px;">def writeVersionInfo(targetDir): 
     open(targetDir, "wb").write("Revison:")</span>

使用python腳本進行文件的操作是非常方便的的。省卻非常多時間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM