Last active
June 4, 2021 11:53
-
-
Save abhinav4848/a1ebe0c8b5c2370b3f35692e368f8530 to your computer and use it in GitHub Desktop.
Python code to reduce a clutter of files into set of folders each having a fixed number of files
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
# make sure your code file is in the base folder of "test" which contains all files to be sorted | |
import os | |
# we'll use this to increment folder count | |
i = 0 | |
# set subfolder name here | |
workingfolder = 'test' | |
# move currentworkingdirectory to "test" folder | |
if not os.path.basename(os.getcwd()) == workingfolder: | |
os.chdir(os.path.join(os.getcwd(), workingfolder)) | |
# only include files in the list. Not folders. Using for-if list comprehension | |
files = [f for f in os.listdir() if os.path.isfile(f)] | |
for count, filename in enumerate(files): | |
# check if current file number is divisible by given number. | |
# If yes, make a new folder | |
if count % 2 == 0: | |
try: | |
i += 1 | |
os.makedirs('set-' + str(i)) | |
except Exception as e: | |
pass | |
# print(count, filename) | |
try: | |
# move the file | |
startpath = os.path.join(os.getcwd(), filename) | |
endpath = os.path.join(os.getcwd(), os.path.join("set-"+str(i), filename)) | |
os.rename(startpath, endpath) | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment