2016-08-25 67 views
0

我想要此功能刪除文件。它正確地做到了這一點,但它刪除我不想要的文件夾。刪除文件開始於

我也執行過程中出現錯誤:

Access is denied: 'C:/temp3\\IDB_KKK 

在文件夾TEMP3我有:

IDB_OPP.txt 
IDB_KKK - folder 

代碼:

def delete_Files_StartWith(Path,Start_With_Key): 
    my_dir = Path 
    for fname in os.listdir(my_dir): 
     if fname.startswith(Start_With_Key): 
      os.remove(os.path.join(my_dir, fname)) 

delete_Files_StartWith("C:/temp3","IDB_") 
+0

縮短措辭,固定句子結構,改進代碼格式。 – Prune

回答

2

使用下,檢查它是否是目錄:

os.path.isdir(fname) //if is a directory 
0

是否要遞歸刪除文件(即,包括生活在子目錄中的文件Path),而不刪除這些子目錄本身?

import os 
def delete_Files_StartWith(Path, Start_With_Key): 
    for dirPath, subDirs, fileNames in os.walk(Path): 
     for fileName in fileNames: # only considers files, not directories 
      if fileName.startswith(Start_With_Key): 
       os.remove(os.path.join(dirPath, fileName)) 
1

刪除一個目錄及其所有內容,use shutil

shutil模塊提供了許多關於文件和文件集合的高級操作。

請參閱問題How do I remove/delete a folder that is not empty with Python?

import shutil 

.. 
    if fname.startswith(Start_With_Key): 
     shutil.rmtree(os.path.join(my_dir, fname)) 
+1

這可能是OP想要的(給出足夠寬泛的問題解釋),或*它可能與OP想要的相反(刪除文件而不是*文件夾,如Prune爲v.2編輯所做的解釋) – jez

+0

同意。如果是這種情況,則isdir()檢查是正確的。 – MatsLindh

0

我固定它通過如下:

def delete_Files_StartWith(Path,Start_With_Key): 
    os.chdir(Path) 
    for fname in os.listdir("."): 
     if os.path.isfile(fname) and fname.startswith(Start_With_Key): 
      os.remove(fname) 

感謝大家。