0

Hi everyone I want to remove all files/folder on a specific folder and to do that I wrote the following code : ( I want to remove all of the file/folders on the directory saved in co_directory except packages_with_....txt files however I got an error

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)'

Is there anyone to help me ? thanks a lot

EDIT **co_directory is global variable**

1 Answer 1

1

There are a couple of ways to do this, without using subprocess,

The os module,

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)
3
  • thanks for comment but How could I prevent to remove the files that I dont want to remove /
    – caesar
    Commented Aug 22, 2013 at 14:54
  • @Eday Also, I don't think -rf takes !(a|b| command, you might want to do just this,sudo rm !(packages_with_diff_branches.txt|packages_with_same_branches.txt)
    – user1786283
    Commented Aug 22, 2013 at 14:59
  • thanks for comment.You were right.It wasnt run until I removed -rf option.Thanks again
    – caesar
    Commented Aug 23, 2013 at 7:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.