Created
April 19, 2013 11:05
-
-
Save akaihola/5419670 to your computer and use it in GitHub Desktop.
A Python script for moving a given list of files to a separate subdirectory while maintaining the directory structure.
This file contains 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 python | |
"""Move listed files to a separate tree | |
Usage:: | |
cd /root/of/files | |
python mover.py <list-of-files.txt # only lists what will be moved | |
python mover.py -x <list-of-files.txt # actually moves the files | |
If any of the listed files is missing, the script terminates with an error. | |
Example: | |
If ``/tmp/list-of-files.txt`` contains:: | |
first.txt | |
subdir/second.txt | |
and we have on the disk:: | |
/tmp/test/mover.py | |
/tmp/test/first.txt | |
/tmp/test/third.txt | |
/tmp/test/subdir/second.txt | |
/tmp/test/anothersubdir/fourth.txt | |
and we do:: | |
cd /tmp/test | |
python mover.py </tmp/list-of-files.txt | |
then no files will yet be moved, but we get the output:: | |
/tmp/test/first.txt | |
/tmp/test/subdir/second.txt | |
If we then run:: | |
python mover.py -x </tmp/list-of-files.txt | |
then we'll get the same output, and have this on the disk:: | |
/tmp/test/mover.py | |
/tmp/test/third.txt | |
/tmp/test/anothersubdir/fourth.txt | |
/tmp/test/MOVED/first.txt | |
/tmp/test/MOVED/subdir/second.txt | |
""" | |
import argparse | |
import os | |
import shutil | |
import sys | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--execute', '-x', action='store_true') | |
args = parser.parse_args() | |
for line in sys.stdin: | |
filepath = line.strip() | |
if not filepath: | |
break | |
assert os.path.isfile(filepath), '{0} not found'.format(filepath) | |
directory = os.path.dirname(filepath) | |
target_directory = os.path.join('MOVED', directory) | |
try: | |
os.makedirs(target_directory) | |
except OSError: | |
pass | |
target_filepath = os.path.join('MOVED', filepath) | |
if args.execute: | |
shutil.move(filepath, target_filepath) | |
print filepath | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment