Consider my root dir ls
gives the following output:
1 2 3 4 a b c d
Some files and some dirs. I want to remove all except a few. I can do :
out = subprocess.check_output(['['find', '.', '-maxdepth', '1', '!', '-iname', 'a', '!' '-iname', 'b', '!' '-iname', 'c', '!' , '-iname', 'd', '-exec', 'rm', '-rf', '{}' , '+'])
But I want to specify all not to delete dirs and files in a list instead of making the command so long, and tough to read, ie, something like:
goodfilesList = ['a', 'b','c', 'd']
out = subprocess.check_output(['find', '.', '-maxdepth', '1', '!', '-iname'] + goodfilesList)
You can try list compression to create the command you want.
something like:
flist = ['a','b','c']
command = ['find', '.', '-maxdepth', '1']
[command.extend(['!','-iname',fname]) for fname in flist] # command == ['find', '.', '-maxdepth', '1', '!', '-iname', 'a', '!', '-iname', 'b', '!', '-iname', 'c']
command.extend(['-exec', 'rm', '-rf', '{}' , '+'])
out = subprocess.check_output(command)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.