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)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for comment but How could I prevent to remove the files that I dont want to remove /
@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)
thanks for comment.You were right.It wasnt run until I removed -rf option.Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.