Last active
October 25, 2016 18:19
-
-
Save ateucher/0d338a969ac67e52190a327f408d40cb to your computer and use it in GitHub Desktop.
In a folder full of files, subsets of which have the same base filename but different extensions (e.g., foo.txt, foo.csv, foo.tar.gz, bar.txt, bar.csv, bar.tar.gz), create folders based on the base filename (e.g., foo, bar) and move the files into the appropriate folders.
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
### Usage: | |
# Copy this file into the directory containing the files, | |
# open a terminal/cmd prompt in that directory, and type: | |
# python move_files.py | |
import os | |
question = "Would you like to move all of the files in '" + os.getcwd() + "' into subfolders? (y/n)" | |
answer = raw_input(question) | |
if answer.lower() != "y": | |
print("Exiting...") | |
exit() | |
all_files = os.listdir(".") | |
files = [f for f in all_files if f != 'move_files.py'] # remove move_files.py from list of files to move. | |
for file in files: | |
# get part of filename before first dot to use for folder name (eg. foo.tar.gz -> foo, or bar.tif.aux.xm -> bar) | |
base = file.split(".")[0] | |
if base == '': # ignore files that begin with . | |
continue | |
if not os.path.isdir(base): | |
print("Creating directory '" + base + "'") | |
os.mkdir(base) | |
print("Moving '" + file + "' to '" + base + "'") | |
os.rename(file, base + "/" + file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment