Last active
June 24, 2020 06:15
-
-
Save mrcrnkovich/6bbe04968a5c2c4bda5e431af5992a4a to your computer and use it in GitHub Desktop.
#script to sort files by suffix into folders
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
''' | |
This is a command line program designed to identify and | |
group all files (non-directories) in a given directory and | |
move each file type (“.csv”, “.py”, “.txt”, etc) into a named | |
directory of the file type. The program will create a new directory | |
for any file type that does not have a directory but will not overwrite | |
existing directories. The program takes the following arguments: | |
directory: a string path to the directory to be organized | |
-v: verbose output option | |
''' | |
import os | |
import shutil | |
from sys import exit | |
import argparse | |
from pathlib import Path | |
verbose = False | |
def main(current_dir: 'Path', file_types: 'list'): | |
'''function receives Path object ('current_dir') and list of file_types''' | |
for folder in file_types: | |
# check if directory exists, create directory if it does not exist | |
if os.path.exists(folder): | |
if verbose: | |
print(f'{folder}: already exists') | |
else: | |
os.mkdir(folder) | |
if verbose: | |
print(f'{folder}: created') | |
move_files(current_dir, folder) | |
def move_files(current_dir: 'Path', folder_name: 'str'): | |
'''function to move files to directory of file type | |
(i.e. "example.csv" to folder "csv")''' | |
for file in current_dir.glob("*."+folder_name): | |
shutil.move(file.name, folder_name+"/"+file.name) | |
if verbose: | |
print(f'{folder_name} successfully moved') | |
def change_dir(new_dir: 'str'): | |
if os.path.isdir(new_dir): | |
try: | |
os.chdir(new_dir) | |
return | |
except: | |
print(f'Can not open {new_dir}') | |
else: | |
print(f'{new_dir} does not exist') | |
print("Exiting...") | |
exit() | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Folder Location") | |
parser.add_argument('directory', help="enter complete directory location") | |
parser.add_argument('-v', dest='verbose', | |
action='store_const', | |
default=False, | |
const=True, help="Verbose output option") | |
args = parser.parse_args() | |
verbose = args.verbose | |
change_dir(args.directory) | |
current_dir = Path('.') | |
file_types = list(set([x.suffix[1:] | |
for x in current_dir.iterdir() | |
if x.is_file()])) | |
if '' in file_types: | |
file_types.remove('') | |
main(current_dir, file_types) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment