2013-04-16 146 views
-4

我想創建一個Python腳本來刪除C:\Windows\CSC\v2.0.6\namespace下的每一個 我需要一個想法..要做到這一點在命令行我必須去cmd然後,一個比psexec -s cmd我不得不轉到C:\Windows\CSC\v2.0.6\namespace比RD *什麼都夾有..我想創建一個腳本來刪除所有..任何幫助腳本刪除C: Windows CSC v2.0.6 namespace

+2

到目前爲止你有什麼? – thegrinner

回答

2

此代碼應刪除您的目錄中的任何文件或目錄:

import os, shutil 
folder = "C:\Windows\CSC\v2.0.6\namespace" 
for item in os.listdir(folder): 
    path = os.path.join(folder, item) 
    try: 
     os.unlink(path) # delete if the item is a file 
    except Exception as e: 
     shutil.rmtree(path) # delete if the item is a folder 

這已是answered previously

+0

我對他的問題「有什麼文件夾......刪除所有」的理解聽起來像他正在尋找遞歸的東西。 –

+0

好點,我添加了刪除文件夾以及文件的代碼。 – Ecliptica

+0

不錯,你先生得到upvote。 –

0

一個simple Google search和一些修改:

import os 
mainPath = "C:\Windows\CSC\v2.0.6\namespace" 
files = os.listdir(mainPath) 
for f in files: 
    os.remove('{}/{}'.format(mainPath, f)) 

如果你想遞歸地發現所有的文件,然後將它們全部刪除(這是一個小劇本我寫了昨天):

import os, os.path 
def getAllFiles(mainPath): 
    subPaths = os.listdir(mainPath) 
    for path in subPaths: 
     pathDir = '{}\{}'.format(mainPath, path) 
     if os.path.isdir(pathDir): 
      paths.extend(getAllFiles(pathDir, paths)) 
     else: 
       paths.append(pathDir) 
    return paths 

那麼你可以這樣做:

files = getAllFiles(mainPath) 
for f in files: 
    os.remove(f) 

注意:遞歸算法得到som如果存在太多的子文件夾(它會創建大量的遞歸節點),會有些緩慢(並且可能會引起MemoryError)。

爲了避免這種情況,你可以使用遞歸函數作爲一個輔助功能,它是由一個主迭代函數調用:

def getDirs(path): 
    sub = os.listdir(path) 
    paths = [] 
    for p in sub: 
     pDir = '{}\{}'.format(path, p) 
     if os.path.isdir(pDir): 
      paths.extend(getAllFiles(pDir, paths)) # getAllFiles is the same as above 
     else: 
      paths.append(pDir) 
    return paths 

它得到然而我們放慢了非常大的子文件夾。通過C:\Python27\Lib需要大約6-7秒(它有大約5K +的文件,以及許多子文件夾)。