Created
May 6, 2013 16:56
-
-
Save jl2/5526388 to your computer and use it in GitHub Desktop.
Create a directory for every file in the specified directory and move the file into it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import os | |
| import sys | |
| import glob | |
| import shutil | |
| import argparse | |
| from stat import * | |
| def main(args): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--directory', help='The directory to search', default=None) | |
| pargs = parser.parse_args(args) | |
| if pargs.directory is None: | |
| print("No directory given!") | |
| return 1 | |
| print('Making one directory for each file in {}, named after the file and moving the file into it'.format(pargs.directory)) | |
| for fn in glob.glob(pargs.directory + '/*'): | |
| mode = os.stat(fn).st_mode | |
| if S_ISREG(mode): | |
| print("Found file {}".format(fn)) | |
| if not os.path.exists(fn+'_tmp'): | |
| try: | |
| os.mkdir(fn+'_tmp') | |
| except: | |
| print("Caught an exception with mkdir for {}".format(fn)) | |
| try: | |
| shutil.move(fn, fn+'_tmp') | |
| except: | |
| print("Caught an exception with move for {}".format(fn)) | |
| try: | |
| os.rename(fn+'_tmp', fn) | |
| except: | |
| print("Caught an exception with rename for {}".format(fn)) | |
| else: | |
| print('Could not create temp directory for {}'.format(fn)) | |
| if __name__=='__main__': | |
| main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment