Skip to content

Instantly share code, notes, and snippets.

@raspi
Created May 31, 2014 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raspi/2a2abd95ba5c2444cd93 to your computer and use it in GitHub Desktop.
Save raspi/2a2abd95ba5c2444cd93 to your computer and use it in GitHub Desktop.
Remove file from directory if it's the only one there including sub-directories.
#!/bin/env/python
# -*- encoding: utf8 -*-
# Remove file from directory if it's the only one there including sub-directories.
# usage: script.py <file to find> <directory>
# script.py readme.txt /stuff/files/misc
import os
import sys
fn = None
if len(sys.argv) > 1:
fn = sys.argv[1]
if fn == "":
fn = None
if fn is None:
print "invalid filename"
sys.exit(1)
topdir = sys.argv[2]
if not os.path.isdir(topdir):
print "invalid directory"
sys.exit(1)
for dirpath, dirnames, files in os.walk(topdir):
if len(files) == 1 and files[0].lower() == fn.lower() and len(dirnames) == 0:
filename = os.path.join(dirpath, files[0])
os.remove(filename)
print "Removed: " + filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment