Skip to content

Instantly share code, notes, and snippets.

@mentix02
Created April 4, 2019 18:53
Show Gist options
  • Save mentix02/8baff0b2e7e59b9b0a5d8860d363dde8 to your computer and use it in GitHub Desktop.
Save mentix02/8baff0b2e7e59b9b0a5d8860d363dde8 to your computer and use it in GitHub Desktop.
removes all file in current directory except for the ones mentioned - hence the name - rm EXCEPT
#!/usr/bin/env python3
import os
import sys
NAME = 'rme'
USAGE = 'usage: {} [FILE]...'.format(NAME)
args = sys.argv # simply because I don't like 'argument vector'
if len(args) == 1:
print('rm: missing operand')
print(USAGE)
exit(1)
del args[0] # remove the first argument that is the file that was executed
current_dir_files = os.listdir('.')
if '--help' in args or '-h' in args:
print(USAGE)
print('removes all files / directories in current file except the ones mentioned')
exit(0)
for file in args:
if file not in current_dir_files:
print('file {} doesn\'t exist in current directory. please check again.'.format(file))
files = [file for file in os.listdir() if file not in args] # args is now only the files provided
for file in files:
try:
if os.path.isdir(file):
os.rmdir(file)
continue
os.remove(file)
except Exception as e:
print('an unknown exception occured:\n{}'.format(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment