2013-08-22 79 views
0

嗨,大家我想刪除特定文件夾上的所有文件/文件夾,並做到這一點我寫了下面的代碼:(我想刪除保存在目錄中的所有文件/文件夾除了packages_with _.... txt文件,但是我得到了一個錯誤使用python.subprocess爲終端命令

def remove_file(): 

    remove="sudo rm -rf !(packages_with_diff_branches.txt|packages_with_same_branches.txt)" 
    p = subprocess.Popen(""" 
    %s 
    %s""" % (co_directory,remove),shell=True , executable='/bin/bash') 
    p.wait() 





/bin/bash: -c: line 3: syntax error near unexpected token `(' 
/bin/bash: -c: line 3: ` sudo rm -rf !(packages_with_diff_branches.txt|packages_with_same_branches.txt)' 

co_directory是否有任何人幫助我嗎?非常感謝

編輯 ** co_directory是全局變量**

回答

1

有幾個方法可以做到這一點,而無需使用subprocess

os模塊,

import os 

filesInDir= [ i for i in os.listdir("/path/to/dir") if i != "yourFile.txt" if i! = "yourFile.txt2" ] 
for i in filesInDir: 
    os.remove(i) 
+0

感謝對此事發表評論,但我怎麼能防止刪除我不想刪除/ – caesar

+0

您的文件可以添加一個條件,檢查編輯。 – enginefree

+0

@Eday此外,我不認爲'-rf'帶'!(a | b |'命令,你可能想這樣做,'sudo rm!(packages_with_diff_branches.txt | packages_with_same_branches.txt)' – enginefree