Question: I want to make sure that I delete required files.
I have code something like

```
dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)

```

The `dir` and `file` values are fetched from a database. How can I make sure I never end up running `rm -rf /`? 

What things should I check before doing `rm -rf`?

Answer: 
Don't use the `-r` switch if you just want to remove a single file. Also, there could be spaces in the file name.

Better use the functions in Python's [`os`](http://docs.python.org/library/os.html) module instead:

```
dirname = "/some/path/"
filename = "somefile.txt"
pathname = os.path.abspath(os.path.join(dirname, filename))
if pathname.startswith(dirname):
   os.remove(pathname)

```

Normalizing the path with [`abspath`](http://docs.python.org/library/os.path.html#os.path.abspath) and comparing it against the target directory avoids file names like "../../../etc/passwd" or similar.
Use `shutil.rmtree` as Dave Kirby says. If you want to delete the just the file use:

```
dir = "/some/path/" 
file = "somefile.txt" 
cmd = os.path.join(dir, file) 
shutil.rmtree(cmd) 

```

If you want to delete the directory use:

```
dir = "/some/path/" 
file = "somefile.txt"  
shutil.rmtree(dir) 

```

If the files are write protected make sure you have write permissions before you run this.