0

Python File Sorter

# sys required to access arguments
import sys;

from os import listdir, makedirs; # listdir required to access OS-related stuff
from os.path import isfile, isdir, join; # required to determine whether something is a file

from shutil import move; #lets us move files

# get the path from the cli arguments
path = sys.argv[1];

# get a list of files
files = listdir(path);

for file in files:
 # check if it is a file
 if isfile(join(path,file)):
 #if so, determine whether this is renameable
 if file[0] == '[':
 # grab the next three letters, filter out spaces
 prefix = file.replace(' ', '').lower()[1:4];
 # check to make sure closing bracket is not in prefix
 if prefix.find(']') == -1:
 # check if directory already exists
 if not isdir(join(path,prefix)):
 makedirs(join(path,prefix));
 
 filepath = join(path,file);
 destpath = join(path,prefix);
 move(filepath,destpath);

I’m starting to get into Python a bit more lately. As a practice run, I re-scripted this old file sorter I had done years ago in bash.

The script should take a directory as a parameter and sort the contents within into folders based on the three-letter prefix of the files. For this to work, the files do need to be named in that weird way comics seem to be, i.e.

[Author] Title Vol Issue.cbr

It will then create a series of subdirectories based on the author name and move the file there, i.e.

./aut

…or if the directory exists, the file will just be moved there without creating a new folder.

Project Info

Client: Self

Services

  • Scripting

Leave a Reply